www.MarqueeGroup.ca
March 6, 2020
VBA & Macros
Seminar for the
1
The Marquee Group
LEADERS IN FINANCIAL MODELING SINCE 2002
• We believe that spreadsheet-based financial models are the most important decision-making tools in modern finance
• We have developed a framework and discipline for model design, structure and development that leads to best-in-class, user-friendly financial models
• We help finance professionals use this framework to turn their models into powerful communication tools that lead to better, more effective decisions
TRAINING
The Marquee Group Offering
CONSULTING ACCREDITATION
© 2016 The Marquee Group Inc.
✓ Instructors have real-world experience and a passion for teaching
✓ Topics include: Modeling, Valuation, Excel, VBA, Power BI, Python
✓ Courses are interactive
✓ Clients include banks, corporations, business schools and societies
✓ Services include:
– Model Development
– Model Re-builds
– Model Reviews and Audits
– Dashboard and Report Design
✓ Clients include a wide range of companies in various industries
✓ Offered by the FinancialModeling Institute (FMI)
✓ The FMI was established by The Marquee Group and ModelOff
✓ FMI administers official exams for three levels of financial modeling certifications
CFA
Otta
wa
- VBA
- M
ar. 2
020
The Financial Modeling Institute
© 2016 The Marquee Group Inc. 2
SKILL VALIDATION• Demonstrate financial modeling proficiency to employers and clients
PERSONAL DEVELOPMENT• Earn certifications that are challenging and revered by the industry
CAREER FLEXIBILITY• Verify skills that are globally relevant and respected in many industries
LEVEL 1 LEVEL 2 LEVEL 3
✓ Foundational level of certification program
✓ Proficiency in building beginner-to-intermediate financial models
✓ Skills in design and comprehension of finance, business, accounting and Excel
✓ Attainable following successful completion of Level 1
✓ Thorough understanding of real-world applications of financial modeling
✓ Demonstrated ability in advanced Excel, financial analysis, and financial modeling
✓ Highest level of accreditation achievable✓ Expert in the end-to-end financial
modeling value chain✓ Respected thought leader, mentor, and
contributor to financial modeling education
EACH LEVEL IS RECOGNIZED AS ITS OWN QUALIFICATION
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 3
Table of ContentsSection Page
Power and Pitfalls of VBA 4
Modeling Discipline & Basics 6
Introduction to VBA, Objects, and Hierarchy 8
The Visual Basic Editor (VBE) 12
Modules 16
Message & Input Boxes 19
VBA Defined Constants 25
Running a Macro 26
Range & Cells Objects 27
Commenting 30
Common Error Types 31
Variables & Setting Objects 32
With…End With Statement 34
Objects – Positions and Sizing 35
Recording a Macro 36
For…Next Loop 37
Decision Making (If…Then) 38
Do Loops 39
For Each…Next Loop 41
Calling Subroutines 42
User Forms 44
User Defined Functions 50
VBA Shortcuts 51
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 4
Power of VBA
• Macros can provide powerful efficiencies when using Excel
– Automate frequent, tedious, or repetitive tasks
– Automate a long series of simple tasks
– Advanced user interfaces
– Use functions that are not easily done in Excel
• Why learn VBA?
– Create powerful automation and efficiency tools
– Knowledge of VBA helps when reviewing workbooks with Macros
– Many advanced applications use VBA in certain circumstances (E.g. custom functions on trading desks)
• Lots of usable VBA code readily available
– Large set of resources and pre-made solutions online (Google, Microsoft website, blogs, forums, etc.)
– Be careful of quality of pre-made code; solutions may be poorly designed, error prone, or not perfectly applicable to your needsC
FA O
ttaw
a - V
BA -
Mar
. 202
0
© 2016 The Marquee Group Inc. 5
Pitfalls of VBA
• Considerations before using macros in Excel workbooks
1. VBA coding language needs to be learned and understood well in order to avoid common errors
2. Macros posses all the same critical attributes of the financial models that they serve
3. Security warnings; macros may need to be enabled via the Trust Center (Alt F T)
4. Buggy macros do not instill confidence in end users
5. Writing code, testing code, and debugging code in VBA may take longer than doing something manually in Excel
6. VBA error messages are often ambiguous
7. Excel probably already has alternate functionality available
8. Macros can make major incorrect changes to Excel files by accident
9. NO UNDO!!
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 6
Modeling Discipline
• The following are important attributes of a strong financial model:
1. Dynamic
2. Flexible
3. Intuitive
4. Printable
5. Transparent
6. Transferable
• When a model achieves the criteria above, it creates tremendous credibility for the builder and inspires confidence with the reader
• It is also much easier for someone to take ownership of a model that meets the criteria above
• In spreadsheets with macros, these all become even more important
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 7
Modeling Basics
• Keep it simple
• NEVER HARDCODE!
– Always enter inputs as a different colour than calculations
– Never enter a formula that looks like:
=A5 * .025 + 4.9
• Use the keyboard to increase speed
• Use comments to label everything properly (even excessively)
• Everything should be printable
• Master the basics
• Become an expert at formatting
• Practice
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 8
What is VBA?
Visual Basics for Applications
• Programming language for Microsoft Office
• Built into most Microsoft Office applications (Excel, Word, Outlook, Access)
• Event-driven programming language
• Object-oriented programming language
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 9
VBA Objects & Hierarchy
• An object represents an element of Excel, such as a workbook, a worksheet, a range, or a chart.
• A collection is an object that contains several other objects
– Example: all the worksheets (each an object itself) in a workbook are contained in a single collection (called Worksheets)
• Example hierarchy of objects
Application (Excel)
Workbook
Worksheet
Range
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 10
Object Properties
• Using properties and methods, you can modify a single object or an entire collection of objects
• A property is an attribute of an object or an aspect of its behavior. For example, properties of a worksheet include its name, its position, and its colour, as well as whether or not protection is turned on
• To change the characteristics of an object, you change the values of its properties
• To set the value of a property, follow the reference to an object with a period, the property name, an equal sign, and the new property value
Sheets(“Sheet1”).Visible = True
Object
Property
ValueCFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 11
Object Methods
• A method is an action that an object can perform. For example, VBA can tell a cell on a worksheet to delete its contents, autofit or copy itself
• Methods can also have arguments that affect how the action is completed. For example, VBA can tell a worksheet to move or recalculate itself
• To make an object do an action using a method, follow the reference to an object with a period and the method name
– Sheets(“Sheet1”).Rows(1).Delete Deletes the first row of cells on tab Sheet1
• In general, properties are attributes and methods are actions:
– Properties: either tell information about an object or change an attribute of the object
– Methods: make something happen to an object
Object Method
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 12
Visual Basic Editor (VBE)
• The Visual Basic Editor (VBE) is where macros and other VBA elements are created, modified and saved
• To access the VBE, first enable the Developer toolbar on your screen by doing the following:
Excel 2010+: ➢ File ➢ Options ➢ Customize Ribbon ➢ Put a check mark in Developer ➢ Click OK
• Once enabled, go to the Developer toolbar and click the Visual Basic icon to open the Visual Basic Editor (Alt+F11)
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 13
Project Explorer
• The Project Explorer is a window in the VBE that displays a list of all active VBA projects/Excel workbooks.
• A project is a collection of VBA code associated with the Excel workbooks and Add-ins that are currently open or active in Excel
• For each project, a hierarchical list of the projects and all of the items contained and referenced by each project is shown.
• (VBE Shortcut Key: Ctrl + R)
Typical elements are:
• An entry for each sheet of the workbook (Document Module)
• An entry for the workbook itself
• A list of each UserForm (customized Excel dialogue boxes)
• A list of each Module (an expandable item in which the majority of macro coding is done)
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 14
Properties Window
• The Properties Window can be used to view and change the attributes of the currently selected object (an object can be selected by clicking on it)
• The Properties window displays different types of editing fields, depending on the needs of a particular property of a particular object. These edit fields types can include edit boxes and drop-down lists.
• (VBE Shortcut Key: F4)
• The properties list is unique to each object
• For example, a Worksheet object has 13 properties which can be edited in the Properties Window, including:
– (Name): the object codename used in VBA
– Name: the tab name as it appears in Excel
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 15
Macros
• A macro is a set of programming code that will automate tasks in Excel when it is ‘run’, ‘executed’ or ‘triggered’.
• In VBA, what is the difference between a ‘macro’, a ‘subroutine’, and a ‘procedure’? Nothing!
• These words are used interchangeably to describe the set of code.
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 16
Modules
• Modules are the main location in VBA that code is written and modified
• They can contain a number of elements, including macros (both subroutines and user defined functions), variables, and English descriptions of code
• Procedures are public (callable by other procedures in other modules) by default, but can be made private (only callable by other procedures in the same module)
• (VBE Shortcut key for adding a new module: Alt, I, M)
CFA
Otta
wa
- VBA
- M
ar. 2
020
17
Adding a Module
• VBA code is most often created and stored, in a module via the Visual Basic Editor (VBE)
• To add a Module, first open the VBA Editor
– Keyboard Shortcut: Alt + F11 also brings up the VBA Editor
• While in the VBA Editor, insert a Module:
Excel 2010
➢ Developer [L] ➢ Visual Basic [V]
Excel 2013
➢ Developer [L] ➢ Visual Basic [V]
Excel 2013
➢Insert [I] ➢ Module [M]
Excel 2010
➢ Insert [I] ➢ Module [M]
© 2016 The Marquee Group Inc.
CFA
Otta
wa
- VBA
- M
ar. 2
020
18
Naming Rules in VBA
• When naming certain things in VBA (e.g. procedures and variables) the following naming rules must be adhered to:
– The first character must be a letter
– Names cannot contain spaces, periods, or exclamation points
– Names cannot contain the following characters: @, &, $, #
– Names cannot be repeated within the same level of scope (e.g., two variables named “Date” cannot be declared within the same procedure)
– Names cannot exceed 255 characters
• In addition, the following are some naming best practices:
– Names should not be the same as functions, statements, or methods
– Use underscore between each new word or have each new word in a name be capitalized
– Long or frequently used names should be input as an abbreviation
© 2016 The Marquee Group Inc.
CFA
Otta
wa
- VBA
- M
ar. 2
020
19
MsgBox
• Message boxes (MsgBox) can be used to convey information to a spreadsheet user through an Excel dialog box
– MsgBox prompt, [buttons], [title], [helpfile], [context]
MsgBox has 1 mandatory argument:
• Prompt: Message that is displayed in the dialog box (string expression)
MsgBox has 4 optional arguments:
• Buttons: Specifies the number and type of buttons to display, style of icon to use, default button identity, and the modality of the message box (numeric expression)
• Title: Title that is displayed in the title bar of the dialog box(string expression)
• Helpfile: Identifies the help file to be used for the dialog box (string expression)
• Context: Represents the help context number that is assigned to the help topic (numeric expression). If this is provided, “Helpfile” must be provided.
19© 2016 The Marquee Group Inc.
CFA
Otta
wa
- VBA
- M
ar. 2
020
• A simple MsgBox macro can be created using the following code:
• Indentation and line spacing are not required, but makes code easier to read
20
MsgBox (Cont’d)
20
“msgbox_example” is the user created name for the macro
“()” brackets are required (will auto-populate)
“Sub” & “End Sub” keywords
are required to define the
macro
When code is run, creates
© 2016 The Marquee Group Inc.
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 21
MsgBox (Cont’d)
• MsgBox can also receive information from users. The buttons displayed by a message box can be modified by changing the Buttons argument
– MsgBox prompt, [buttons], [title], [helpfile], [context]
• Msgbox requires brackets if used to assign value to a variable
Button Type Result
vbOKOnly Displays OK button only.
vbOKCancel Displays OK and Cancel buttons.
vbAbortRetryIgnore Displays Abort, Retry, and Ignore buttons.
vbYesNoCancel Displays Yes, No, and Cancel buttons.
vbYesNo Displays Yes and No buttons.
vbRetryCancel Displays Retry and Cancel buttons.
vbCritical Displays Critical Message icon.
vbQuestion Displays Warning Query icon.
vbExclamation Displays Warning Message icon.
vbInformation Displays Information Message icon.
vbDefaultButton1 First button is default.
vbDefaultButton2 Second button is default.
vbApplicationModal The message box requires user response to proceedCFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 22
MsgBox (Cont’d)
• Example: Returns the user’s option of either aborting code, retrying the code, or ignoring the error (with the 2nd button preselected)
user_option = MsgBox(“Your Message”, vbAbortRetryIgnore + vbDefaultButton1)
• This line of code will produce:
• And the user’s choice will be assigned to the variable user_option in the form of a numeric value
Button Clicked Button Type Value
OK vbOK 1
Cancel vbCancel 2
Abort vbAbort 3
Retry vbRetry 4
Ignore vbIgnore 5
Yes vbYes 6
No vbNo 7
• I.e. if the user selects ‘Abort’, the value of user_option will be 3. If ‘Ignore’ is chose, then the value will be 5.
• We can then make the program do different things based on this valueC
FA O
ttaw
a - V
BA -
Mar
. 202
0
23
InputBox
• Similar to a MsgBox, an InputBox can be used to prompt a dialog box for a user to input a value
• InputBox(prompt, [title], [default], [Xpos], [Ypos], [helpfile], [context])
InputBox has 1 mandatory argument:
• Prompt: Message that is displayed in the dialog box (string expression)
InputBox has 6 optional arguments:
• Title: Title that is displayed in the title bar of the dialog box(string expression)
• Default: Default response displayed in the text box if no other input is provided (string expression)
• Xpos: The horizontal distance of the left edge of the dialog box from the left edge of the screen (numeric expression)
• Ypos: The vertical distance of the upper edge of the dialog box from the top of the screen (numeric expression)
• Helpfile: Identifies the help file to be used for the dialog box (string expression)
• Context: Represents the help context number that is assigned to the help topic (numeric expression). If this is provided, “Helpfile” must be provided.
23© 2016 The Marquee Group Inc.
CFA
Otta
wa
- VBA
- M
ar. 2
020
24
InputBox (Cont’d)
• A simple InputBox can be created using the following code:
• This creates the following dialog box:
24
The model user inputs a response here
© 2016 The Marquee Group Inc.
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 25
VBA Defined Constants
• VBA has a number of built-in constants (variables with pre-defined values) that it relies on to run code
• These constants generally start with specific letters and a part of the Microsoft hierarchy
• Types can be specific to VBA (‘vb’), Excel (‘xl’) or Microsoft Office (‘mso’)
• Example of uses of constants:
– MsgBox “Line 1” & vbNewLine & “Line 2”
– Range(“A1”).Font.Color = vbBlue
Miscellaneous Description
vbNewLine Newline character
vbTab Tab character
Colour Codes Description
vbBlack Colour code for Black
vbWhite Colour code for White
vbRed Colour code for Red
vbBlue Colour code for Blue
vbYellow Colour code for Yellow
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 26
Running a Macro
• Macros can be ‘Run’ many different ways in Excel, including:
– Choosing a macro in the Macro dialogue box (Excel: Alt + F8)
– Running a macro from within VBE (VBE: F5)
– Using a user-defined Shortcut Key (Excel: Ctrl + a character chosen by user)
– Clicking on Controls (buttons, dropdown boxes, etc.)
– On an Event such as opening a workbook or editing cells
– Calling a macro from another macro
– Option on the Ribbon or the Quick Access Tool Bar
• Resetting VBA after execution interrupted:
– If execution of a macro is interrupted (either by user or due to error), VBA highlights the line of code where the execution stopped. This is called ‘Break Mode’
– Attempting to run code during break mode results in the VBA error box “Can’t execute code in break mode”
– To reset the code, choose Reset from the VBE Run menu (Alt R R)
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 27
Range & Cells Objects
• Manipulating cells or ranges of cells is one of the most frequent uses of VBA subroutines
• In VBA, like in Excel, you can identify cells and ranges in multiple ways to be used as an object
Object Description
Sheets(“Sheet1”).Range(“A1”) Single cell A1 on ‘Sheet1’ tab
Range(“A1”) Single cell A1 on active tab
Cells(Row,Col) Single cell at intersection of Row and Column on active tab
Range(“F5”).Cells(Row,Col) Single cell Row rows and Col columns away from cell F5
Range(“F5”).OffSet(Row,Col) Single cell Row rows and Col columns away from cell F5
ActiveCell Single cell currently selected in Excel
Range(“A1:B2”) Multi-cell range A1:B2 on active tab
Range(“A1:B2”).OffSet(Row,Col) Multi-cell range (2x2) Row rows and Col columns away from cell A1
Range(Cells(Row1,Col1),Cells(Row2,Col2)) Multi-cell range defined on the position of the Cells1 and Cells2
Range(“Named_Range”) Single cell or multi-cell range defined by a Named Range in Excel
Selection Single cell or multi-cell range currently selection in Excel
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 28
Formatting Cells
• Once a range object is identified, VBA can perform numerous actions
• You can change or retrieve its properties:
• Or apply methods to it:
Statement Result
Range(“B2”).NumberFormat = “0.00%” Changes cell B2 to 2 digit percentage
Range(“C2:F5”).Interior.Color = RGB(255,0,0) Changes cells in range C2:F5 to the colour red
Cells(1,1).Font.Italic Italicizes font in cell A1
Cells(1,1).Font.Bold Bolds font in cell A1
Cells(1,1).Font.Color = RGB(0,0,255) Changes font colour blue in cell A1
Cells(5,4).Comment.Text =“Hello” Changes text of comment attached to cell D5
Statement Result
Range("A1").Formula = "=$A$4+$A$10” Changes formula in A1 to sum A4+A10
Cells(7,5).ClearContents Deletes contents of cell E7
CellFormatVar = ActiveCell.NumberFormat Assigns the current cells number format to the variable CellFormatVar
Selection.Copy Copies currently selected cells (or other objects)
Range(“B2”).FormulaHidden = True Hides formula in cell B2
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 29
Objects - Colours
• VBA handles colours in a wide number of formats in Excel
– There are 16.8 million colours available in Excel
– .Color property is applied when using “More Colors” dialogue boxes
– .RGB(Red, Green, Blue) property is the preferred method of coding colour in VBA. It is made up of three primary color components. Each component can take on a value from 0 to 255.
– With this property you can make the same 16.8 million colour combinations
• To set the background of a cell to green:
– Cells(1,1).Interior.Color = RGB (0, 255, 0)
– The Macro Recorder will record this as Cells(1,1).Interior.Color = 65280, which is equivalent to [(Red x 256^0) + (Green x 256^1) + (Blue x 256^2)]
• To set the font of a cell to blue:
– Cells(1,1).Font.Color = RGB (0, 0, 255)
• Black is the absence of colour [RGB(0, 0, 0)] and white is all colours together [RGB(255,255,255)]C
FA O
ttaw
a - V
BA -
Mar
. 202
0
© 2016 The Marquee Group Inc. 30
Commenting
• Adding descriptions in English to code helps the transferability of a workbook. VBA will ignore these descriptions when code is run.
• Commenting is done by adding a single quotation mark before a sentence
• Common elements to comment on:
– Purpose of the subroutine
– Description of the subroutine
– Short cut key attached (if applicable)
– Author name and information
– Each section
– Complicated lines of code
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 31
Common Error Types
VBA will catch and alert you to certain errors…
– Syntax Errors:
• Errors that the VBE catches while you write code.
• Examples: missing words, parenthesis, etc.
– Compile Errors
• VBA errors that occur during the compilation of your code (before execution).
• Example: some misspelled words (‘Ranges’ instead of ‘Range’).
– Run-time Errors
• VBA errors that occurs during the execution of your code or macro
• Example: Selecting a non-existent object [e.g. Cell(-1,-1).Select]
…but certain errors require attention and auditing:
– Logic Errors
• Errors in the logic of the code which the compiler will not find.
• Example: A macro that is meant to multiply two numbers, but programmer uses “/” instead of “*” for the multiplication sign.
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 32
Variables
• Every programming language has the concept of variables that act much like variables in algebra. They are used to store some type of information that can be used or changed by the program.
• Declaring variables at the beginning of your code is best practice
– Dim X sets up a variable called X
– Declaring variables is not always necessary in VBA (though you can change the VBE settings to require variable declaration)
– If you do not declare a variable, VBA will automatically do so when it comes across a new variable in your code
• Variables can be used for a variety of tasks, including mathematical equations (X = Y * Z), Boolean (X = True), and string manipulation (X = “Hello”)
• Unlike algebra, variables can be added to themselves
– X = X + 1 increases the value of X by 1
• Best practice is to comment in detail so that users understand the code
– Dim X ‘This variable will be used for the following…
• A procedure-level variable is visible only to the sub where it is created
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 33
Setting Object Variables
• Similar to normal variables representing a number or string, object variables represents an object that exists in a workbook
– Example: The object variable ‘my_object’ represents the cell A1 of Sheet1 of Book1
• To assign an object to an object variable, the keyword Set needs to be used at the beginning of the statement
– Set my_object = Workbooks(“Book1”).Worksheets(“Sheet1”).Range(“A1”)
– Set is not used for regular variable declaration
• Code without the object variable:
– Workbooks(“Book1”).Worksheets(“Sheet1”).Range(“A1”) = 100
• Code with the object variable:
– my_object = 100
• Using object variables provide two advantages:
1. The object variable name is shorter, therefore code is less cluttered
2. Instead of writing the same lengthy code 3 times to make changes to A1 then A2 then A3, the code could be written for my_object once, and then re-run with 3 different assignments to my_object (=A1, =A2, =A3)
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 34
With…End With Statement
• The With…End With structure applies a series of statements to a single object. Its main purpose is to make code more readable by eliminating repetitive, redundant qualifying expressions
• To change multiple properties of an object, put the property statements in between the With and End With keywords
• Syntax:
• Example:
With Object‘code
End With
Set My_Object = Workbooks(“Book1”).Worksheets(“Sheet1”).Range(“A1”)
With My_Object ‘selects object to be modified in multiple ways.Value = 5 'puts the number 5 in cell A1.Interior.Color = RGB(0,255,0) 'changes cell A1 background green
End With
CFA
Otta
wa
- VBA
- M
ar. 2
020
35
Objects – Position and Sizing
• Users can specify both the positioning and sizing properties of objects
• Sometimes this is done when an object is created in the Left & Top arguments
– InputBox(prompt, [title], [default], [Left], [Top], [helpfile], [context])
• Existing objects can be modified by adhering to the following syntax, where expression represents an object:
– expression.Left
– Example: ActiveSheet.Shapes("TextBox 1").Top = 100
• Certain objects (i.e. Ranges, Cells, Columns, Rows, etc.) require the use of .ColumnWidth and .RowHeight to edit, but not read, a property
– Example: Cells(1,1).ColumnWidth = 100 ‘ColumnWidth is used to change the cell’s width
– Example: MsgBox Cells(1,1).Width ‘.Width can be used to retrieve the cell’s width
Property Description
.Left The position of the upper left corner of the object relative to the upper left corner of the worksheet (numeric expression). This is measured in points.
.Top The position of the top of the object relative to the top of the worksheet (numeric expression). This is measured in points.
.Width The width of the object, measured in points (numeric expression)
.Height The height of the object, measured in points (numeric expression)
© 2016 The Marquee Group Inc.
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 36
Recording a Macro
• The Macro Recorder in Excel is a powerful tool that allows you to record your actions in Excel and convert them to code automatically
• To start the Macro Recorder, click on the Record Macro icon on the Developer tab
• On the Record Macro dialogue box that appears, you can name the macro to be recorded, and assign it a Shortcut Key, location, and description
Shortcut Keys
• If you choose to assign your macro a Shortcut Key, be sure to use one of the unassigned letters as key combinations assigned to a macro take precedence of built-in Excel shortcut keys
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 37
For…Next Loop
• One of the most powerful aspects of VBA is the ability to repeat small actions multiple or thousands of times
• For…Next loops repeat a block of statements a specified number of times
• They are the simplest type of loop in VBA
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 38
If…Then Statement
• If…Then statements are simple, yet powerful, decision making tools in VBA.
• If…Then statements can be done in a single line
• Or then can be multi-line
CFA
Otta
wa
- VBA
- M
ar. 2
020
39
Do Loops
• Do While…Loop loops repeat a block of statements while a Boolean condition is True
• Do Until…Loop loops repeat a block of statements until a Boolean condition is True
• The follow syntax rules apply to Do Loops:
Do Loops have 3 mandatory arguments:
• Do: Begins the definition of the Do Loop
• While or Until: Repeats the loop until the condition is False or True
• Loop: Ends the definition of the Do Loop
Do Loops have 4 optional arguments:
• Condition: A Boolean expression
• Statements: One or more statements which are repeated While or Until the condition is True
• Continue Do: Control is transferred to the next iteration of the Do Loop
• Exit Do: Control is transferred out of the Do Loop
39© 2016 The Marquee Group Inc.
CFA
Otta
wa
- VBA
- M
ar. 2
020
40
Do Loops (Cont’d)
• The following Do Loop demonstrates the theory behind the Do Until...Loop:
• When the above code is run, range A1:A10 (i.e. Cells(1,1) to Cells(10,1)) will automatically fill with the number 100 since the loop will stop once Counter_Var > 10
40© 2016 The Marquee Group Inc.
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 41
For Each…Next Loop
• For Each…Next loops repeat a block of statements on every object/element in a collection
• Instead of counting through a set of numbers like the For…Next loop, the For Each…Next loops through a set (collection) of objects
Examples: looping through all charts on a sheet, all cells in a range, all worksheets in a workbook
Structure
For Each Object In Collection
‘Code that runs one each Object in turn
Next Object
Example
‘This will run the code in the For
Each…Next loop in each chart
For Each My_Object In ChartObjects
‘Code that runs one each Object in turn
Next My_Object
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 42
Calling Subroutines
• Larger, more complex VBA programs should be created using multiple subroutines. One subroutine can execute another subroutine using the Call keyword.
• For example, the subroutine ‘Main_Macro’ runs (Calls) the subroutine ‘Macro_1’. When ‘Macro_1’ finishes, the program returns to ‘Main_Macro’, which then calls ‘Macro_2’
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 43
Passing Variables
• Procedure-level variables that we have declared (using Dim) can only be used in the procedure in which they are declared. Sometimes we want to pass a value created by one subroutine to another subroutine to do something else with it. We can do that in two ways in VBA:
1. Declare module-level variables (using Public). This is done above the top subroutine in a module:
– E.g. ‘Macro_1’ could set X’s value to 5 and ‘Macro_2’ could times it by 20. If X was not declared at the module level, then its value would revert to zero at the end of ‘Macro_1’
2. Passing arguments using the subroutine brackets
CFA
Otta
wa
- VBA
- M
ar. 2
020
44
Adding a UserForm
• A UserForm is an interface that allows the model user to input data
• This input data then feeds the VBA procedure
• To add a UserForm, first open the VBA Editor
– Keyboard Shortcut: Alt + F11 also brings up the VBA Editor
• While in the VBA Editor, insert a UserForm:
Excel 2010
➢ Developer [L] ➢ Visual Basic [V]
Excel 2013
➢ Developer [L] ➢ Visual Basic [V]
Excel 2013
➢Insert [I] ➢ UserForm [U]
Excel 2010
➢ Insert [I] ➢ UserForm [U]
© 2016 The Marquee Group Inc.
CFA
Otta
wa
- VBA
- M
ar. 2
020
45
UserForms – Control Objects
• Once a UserForm has been added, a Toolbox appears within the UserForm window
• Within the Toolbox, the Controls tab allows for the following functionality (listed in the same position as the image above):
– Select Objects; Label; TextBox; ComboBox; ListBox; CheckBox;
– OptionButton; ToggleButton; Frame; CommandButton; TabStrip; MultiPage;
– ScrollBar; SpinButton; Image; RefEdit
© 2016 The Marquee Group Inc.
CFA
Otta
wa
- VBA
- M
ar. 2
020
46
UserForms – Control Objects (Cont’d)
• The functionality of the control options within the UserForm Toolbox are:
Property Description
Select Objects Allows user to select objects
Label Display information to user
TextBox Allows user to enter text
ComboBox Displays dropdown list of items to select
ListBox Displays list of items to select
CheckBox Allows user to click on and off (returns True/False)
OptionButton Allows user to click on and off (returns True/False)
ToggleButton Allows user to click on and off (returns True/False)
Frame Creates areas within UserForm
CommandButton Button to run macro
TabStrip Add layers to UserForm
MultiPage Add layers to UserForm
ScrollBar Allows user to slide value of bar
SpinButton Allows user to increase or decrease value
Image Inserts an image
RefEdit Allows user to enter a cell range into UserForm
© 2016 The Marquee Group Inc.
CFA
Otta
wa
- VBA
- M
ar. 2
020
47
UserForms – Control Objects (Cont’d)
• Examples of each control option within the UserForm Toolbox:
© 2016 The Marquee Group Inc.
CFA
Otta
wa
- VBA
- M
ar. 2
020
48
UserForms – Control Subroutines
• Each UserForm in a VBAProject has a corresponding code module that can be accessed via View Code. The UserForm code module contains all the UserForm-specific subroutines
• When certain events happen to the UserForm, or the controls located on it, subroutines can be triggered
• For example, if a UserForm contains a button called OKButton and that button is clicked, then some action will be performed by the OKButton_Click subroutine.
• Each type of control has a specific set of events that can trigger a subroutine. The drop down list in the graphic shows the trigger events for a button control.
© 2016 The Marquee Group Inc.
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 49
File Management
• A complex task that finance professionals commonly want to use VBA for is file management
• Opening, manipulating, and saving workbooks with VBA can save some users a lot of time
• It is often helpful to tell VBA what the current directory should be:
– ChDir "C:\Users\TheMarqueGroup\SaveFileDir"
• Excel workbooks can then be opened from, or saved to, this directory using a statement similar to:
– Workbooks.Open Filename:="ExampleOpenFile.xlsm“
– ActiveWorkbook.SaveAs Filename:="ExampleSaveFile.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
• A file directory dialogue box can be displayed and then the chosen file name will be assigned to the variable file_name using this method:
– file_name = Application.GetOpenFilename
– file_name = Application.GetSaveAsFilename
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 50
User Defined Functions
• Excel has hundreds of built-in functions, but sometimes a simple function does not exist for what you may be trying to accomplish.
• Custom User Defined Functions (UDFs) are functions that you develop yourself in VBA. The coding can be as long or short as you want it to be.
• Example: Excel does not have an easy way to find the number of sheets in a workbook. This ‘SheetCount’ function does just that.
– Note that the Sub…End Sub keywords are replaced with Function…End Function
• UDFs can then be used like any other function in Excel and will appear in the auto-formula drop-down
• Note: user designed functions will always be slower than built-in Excel functions
CFA
Otta
wa
- VBA
- M
ar. 2
020
© 2016 The Marquee Group Inc. 51
VBA Shortcuts
Description PC MAC
General
Save Ctrl+S ⌘ + S
Running Macros
From the VBE F5
Macro Dialogue Box Alt+F8
Step Into F8 ⌘ + Shift + I
Reset Code Alt R R
Break Running Code ESC or Ctrl+Break ⌘ + .
Navigation
VBE Alt+F11
Excel Alt+F11
Project Window Ctrl+R ⌘ + Shift + R
Properties Window F4 F6
Code Window F7 F7
Object Browser F2 ⌘ + Shift + B
Immediate Window Ctrl+G ⌘ + Shift + G
Coding
Auto-Fill Code Tab
List Properties/Methods Ctrl+J
Indent Tab
Outdent Shift+Tab
CFA
Otta
wa
- VBA
- M
ar. 2
020