Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
Visual Basic Editor
• The Visual Basic Editor (VBE) is the environment in which you work with VBA programming code.– ALT + F11
• VB Developer Tab– Add it through the Excel Options– Click Visual Basic
Scott J. Mason, Ph.D., [email protected]
2
Visual Basic Editor
• Code is saved in a .xlsm file– Clicking Save in VB Editor or Excel saves both the Excel file
and the VB code
Scott J. Mason, Ph.D., [email protected]
3
Fix Security Settings
• On the Developer Tab, click Macro Security• Click Disable all macros with notification
Scott J. Mason, Ph.D., [email protected]
4
When opening a .xlsm file
• When you see the message below, Enable Content, assuming you know/trust the source of the file!
IE 8580, [email protected]
5
Record Your Own Macro
• Developer Tab• Click Record Macro
– This is how I “learned” to write code when I was kid
• You can assign a hot key to run this macro (e.g., j)
Scott J. Mason, Ph.D., [email protected]
6
Relative/Absolute References
• Relative References On
Scott J. Mason, Ph.D., [email protected]
7
• Relative References Off– Absolute References
Example: Relative References Off
• Record Macro with relative references off– Create a spreadsheet with the text entries as follows, then click Record Macro
• Insert two rows below “Monday”• Move “Robert” cell below “Monday”• Move “Register” cell below “Robert”• Select the cell directly below• Click Stop Recording
Scott J. Mason, Ph.D., [email protected]
8
Example: Relative References Off
• When the macro runs, two rows are inserted below “Monday” again instead of below “Tuesday”
• The rows are always inserted between rows 1 and 2 and cells B1 and C1 are always moved
Scott J. Mason, Ph.D., [email protected]
9
Example: Relative References On
• Record the same Macro with Use Relative References on, then click Stop Recording
• Now the starting cell moves when the macro runs
Scott J. Mason, Ph.D., [email protected]
11
Example: Relative References On
• The VBA code:
• Notice– ActiveCell.Offset([#rows],[#cols]) vs. Range(”B1”)
Scott J. Mason, Ph.D., [email protected]
12
General Steps for Writing a Program
• Get into VB Editor• Add a module• Write a sub (or copy it in this case)• Run the code from VB Editor• Optional (but useful): Add a button to the
spreadsheet to run the code
• We’ll revisit this later in this module!
IE 8580, [email protected]
13