IE 8580 Module 4: DIY Monte Carlo Simulation Lecture 4.1: Visual Basic for Applications 101
Scott J. Mason, Ph.D., mason@clemson.edu 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., mason@clemson.edu
Scott J. Mason, Ph.D., mason@clemson.edu 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 To see a missing window: View: select the window Code Window, Project Window, Properties Window Code window: where the code goes Scott J. Mason, Ph.D., mason@clemson.edu
Scott J. Mason, Ph.D., mason@clemson.edu Fix Security Settings On the Developer Tab, click Macro Security Click Disable all macros with notification Scott J. Mason, Ph.D., mason@clemson.edu
When opening a .xlsm file When you see the message below, Enable Content, assuming you know/trust the source of the file! IE 8580, mason@clemson.edu
Scott J. Mason, Ph.D., mason@clemson.edu 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., mason@clemson.edu
Relative/Absolute References Relative References On Relative References Off Absolute References Scott J. Mason, Ph.D., mason@clemson.edu
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., mason@clemson.edu
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., mason@clemson.edu
Example: Relative References Off The VBA code: Scott J. Mason, Ph.D., mason@clemson.edu
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., mason@clemson.edu
Example: Relative References On The VBA code: Notice ActiveCell.Offset([#rows],[#cols]) vs. Range(”B1”) Scott J. Mason, Ph.D., mason@clemson.edu
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, mason@clemson.edu