Excel Workshop III - UCLAactuary... · WHAT IS VBA? VBA stands for Visual Basic for Applications...
Transcript of Excel Workshop III - UCLAactuary... · WHAT IS VBA? VBA stands for Visual Basic for Applications...
EXCEL WORKSHOP IIIINTRODUCTION TO MACROS AND VBA PROGRAMMING
TABLE OF CONTENTS
1. What is VBA?
2. Safety First!
1. Disabling and Enabling Macros
3. Getting started
1. Enabling the Developer tab
4. Basic VBA
1. Hierarchy
2. Properties & Methods
3. Variables
5. Macro Recorder
TABLE OF CONTENTS
6. Hello World
1. MsgBox
2. OnLoad
7. Buttons
8. Reactions
9. Arrays
10. Example: AddOneYear() to a development triangle
1. Loops / Conditional Statements
2. Custom functions
WHAT IS VBA?
VBA stands for Visual Basic for Applications
Closely related to Microsoft’s Visual Basic
VB is very archaic and now retired
VBA an Object-based Language
Similar to object-oriented languages (C++, Java)
You’ll see variables, for-loops, functions, etc.
Excel workbooks that contain macros are .xlsm files
Normal workbooks are .xlsx
We use VBA to make repetitive or complex jobs easier
SAFETY FIRST!
By default, macros are disabled with notification
Potentially malicious code can run
For example, endless MsgBoxes
You need to enable macros when opening a .xlsm workbook
Only enable macros from sources you trust
Access Macro Settings:
File > Options > Trust Center > Trust Center Settings > Macro Settings
GETTING STARTED
Enable the Developer tab
Right click on the ribbon > Customize ribbon > Check-mark the developer tab
Open the VBA Editor
Click Developer tab > Visual Basic
Or use Alt+F11
The Editor is where you edit VBA modules
Modules consists of Sub procedures and Function procedure
BASIC VBA: HIERARCHY
VBA is object-based
Objects include Workbooks, Worksheets, Cells, and Variables
Objects are organized into a hierarchy:
Application.Workbooks("Book1.xlsx")
Application.Workbooks("Book1.xlsx").Worksheets("Sheet1")
Application.Workbooks("Book1.xlsx").Worksheets("Sheet1").Range(“A1”)
Excel uses the active objects if you omit references
Range(“A1”) refers to Cell A1 on the active worksheet in the active workbook
You can also access cells using column and row number
Cell A2 is Cells(1,2) or Range(“A2”)
BASIC VBA: PROPERTIES & METHODS
Objects have properties
Range("A1").Value 'Returns the content of Cell A1
Range("A1").Width 'Returns the width of the Cell A1
Range("A1").Font
Objects have methods
Range("A1").ClearContents
Workbook("Book1.xlsx").Close
Range("A2:A3").Copy _ 'Underscore indicates continuation to next line
destination:= Range("B2")
'destination is a parameter of the Copy method
BASIC VBA: VARIABLES
Declaring a variable using the keywords Dim and as
Dim myInt as Integer 'Allocates 2 bytes of memory for an Integer
myInt = 100 'Sets the value of the variable
Other commonly used data types include
Double (8 bytes) Used for floating-point numbers (decimals)
Fixed-length String (Size depends on number of characters) Used for text
Dim myString As String * stringLength
Variable-length String (10 more bytes than a Fixed-length String)
Dim myString As String
Boolean (2 bytes ) True (-1) or False (0)
Variant (16 bytes) Can store any kind of data. Slower to process and makes code hard to read.
THE IMMEDIATE WINDOW
Public Sub PrintValue()
Debug.Print "Hello" 'Prints to the immediate window
Debug.Print x 'Prints the value of the variable x
End Sub
• Very useful feature in the VBA Editor
• Open with Ctrl+G or View > Immediate Window
• You can ask questions in the Immediate Window
?Worksheets.Count
?Range("B2").Value
• Debug.Print is useful when you are debugging
RECORDING MACROS
A lot of people learn to code in VBA by recording actions in Excel and reading the
code for those actions.
Step 1: Start recording
Developer > Code > Record Macro
Step 2: Do stuff in your workbook
Step 3: Stop recording
Developer > Code > Stop Recording
Step 4: Read the code in the Editor
Developer > Code > Visual Basic (or Alt+F11)
RECORDING MACROS: EXAMPLE
You have data on ALL Major League Baseball teams’ performance from the past decades
We ask: How has the win-percentage of 1st-place teams in the NL West Division changed over the years?
Generate a linear regression line.
1. Go to the sheet “Using Macro Recorder”
2. Start recording: Developer > Code > Record Macro
3. Activate filtering: Data > Sort & Filter > Filter
4. Filter Column D for NL West
5. Filter Column K for 1st Place Finishes
6. Select Columns B (Year) and I (Win Percentage)
7. Insert > Scatterplot
8. Right-click the plus-sign (+) for Chart Elements, then add Trendline
9. Go to “More Options” for the Trendline and Display Equation and R²
10. Stop recording
RECORDING MACROS: EXAMPLE
Go to Developer > Visual Basic to review the code in the Editor
Sub Macro1()
Selection.AutoFilter 'Activates Filtering
ActiveSheet.Range("$A$1:$V$2565").AutoFilter _
Field:=4, _ 'Filters the 4th column of Selection
Criteria1:="NL West" 'For those in the NL West
ActiveSheet.Range("$A$1:$V$2565").AutoFilter _
Field:=11, _
Criteria1:=Array( "1st of 4", … , "1st of 7"), _
Operator:=xlFilterValues
RECORDING MACROS: EXAMPLE
Range("B:B,I:I").Select
ActiveSheet.Shapes.AddChart2(240, xlXYScatter).Select
ActiveChart.FullSeriesCollection(1).Trendlines.Add
Type:=xlLinear, … ,
DisplayEquation:=0,
DisplayRSquared:=0,
Name:="Linear (W.L.)"
ActiveChart.FullSeriesCollection(1).Trendlines.Add
ActiveChart.FullSeriesCollection(1).Trendlines(2).Select
Selection.DisplayEquation = True 'Displays equation y=mx+b
Selection.DisplayRSquared = True 'Displays R-squared value
Application.CommandBars("Format Object").Visible = False 'Closes sidebar
End Sub
HELLO, WORLD
Let’s try a few different ways to display “Hello World”
Create a new module in the Project Window
Edit the name of the module in the Properties Window (F4)
Write the following code:
Option Explicit 'You must explicitly Dim new variables As a data type
Sub HelloWorld() 'Sets the content of Cell C5 to “Hello World”
ActiveSheet.Range("C5").Value = "Hello World"
End Sub
In Excel, go to Developer > Code > Macros and click HelloWorld to run
HELLO WORLD: MESSAGE BOXES
Create another module in the Project Window
Write the following code:
Option Explicit
Sub HelloWorldPopUp()
MsgBox "Hello World“ 'Generates a pop-up box
End Sub
In Excel, run this HelloWorldPopUp macro
HELLO WORLD: ONLOAD
Create another module in the Project Window
Write the following code:
Private Sub Worksheet_Activate()
MsgBox ("Thank you for coming to the workshop today!")
End Sub
Private Sub Worksheet_Deactivate()
MsgBox ("Bye, I will miss you")
End Sub
In Excel, click this sheet, and then click away to see the MsgBoxes
BUTTONS
You can create a button to run a macro when you click on it
Step 1. Draw a button.
Go to Developer > Controls > Insert > Button (Form Control)
Draw the button
Step 2. Assign a macro.
Right-click on the button > Assign Macro > New/Edit
Type the following code:
Option Explicit
Sub HelloWorld()
ActiveSheet.Range("C5").Value = "Hello World"
End Sub
REACTIONS
You can write a macro to react to a user’s action
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Selection.Count = 1 Then
If Not Intersect(Target, Range("F8")) Is Nothing Then
MsgBox "Hello there"
ElseIf Not Intersect(Target, Range("F10")) Is Nothing Then
MsgBox "Oopsie, wrong button"
End If
End If
End Sub
ARRAYS
An array holds a list of elements of the same data type
There are multiple ways to declare a static array.
Dim myArray(0 To 3) As Integer 'Create array with locations 0,1,2,3
Dim myArray(3) As Integer 'Defaults as 0 to 3 i.e. locations 0,1,2,3
Dim myArray(1 To 5) As Integer 'Locations 1,2,3,4,5
You can set the values of elements
myArray(3) = 97 'Sets the value of the 4th element of myArray to be 97
ARRAYS CONTD.
You can use the Array function to set the values in an array of Variants
Dim arr1 As Variant
arr1 = Array("Orange" , "Peach" , "Pear")
Dynamic Arrays do not need the size to be specified upon declaration
Dim dynArr1() As Variant 'Declares a dynamic array
ReDim dynArr(x+1) 'Sets the size of the array to x+1
ReDim Preserve dynArr(x+3) 'Extends the size of the array by 2 while preserving existing data
DEVELOPMENT TRIANGLE
The development triangle is used to project ultimate losses
The triangle below shows losses for six accident periods (2012, … , 2017)
The loss amount for each accident period is shown at various ages (months after the beginning of the
accident period)
A B C D E F G
1 12 24 36 48 72 84
2 2012 1375 1994 2532 2834 3034 3156
3 2013 1894 2746 3488 3906 4180
4 2014 2214 3210 4077 4566
5 2015 3526 5113 6493
6 2016 5571 8078
7 2017 5876
A B C D E F G
1 12 24 36 48 72 84
2 2012 1375 1994 2532 2834 3034 3156
3 2013 1894 2746 3488 3906 4180
4 2014 2214 3210 4077 4566
5 2015 3526 5113 6493
6 2016 5571 8078
7 2017 5876
DEVELOPMENT TRIANGLE
The triangle below is As of 12/31/2017.
At 12/31/2018, we need to add a row (Acc. Per. 2018) and a column (age 96)
Let’s write a macro called AddOneYear()
EXAMPLE: ADDING A YEAR TO A DEVELOPMENT TRIANGLE
Option Explicit
Sub AddOneYear()
Application … Range("B1").Select 'Begin in Cell B1 (Age 12)
Dim lastAge As Integer 'Will store the rightmost age (Age 84)
'Loop rightward across ages until the rightmost (Age 84) is found
While IsEmpty(ActiveCell) = False
lastAge = ActiveCell.Value 'Store value as lastAge found
'Select one cell to the right
ActiveCell.Offset(0, 1).Select
Wend
ActiveCell.Value = lastAge + 12 'Adds Age 96 to the right
EXAMPLE: ADDING A YEAR TO A DEVELOPMENT TRIANGLE
Range("A2").Select
Dim lastYear As Integer
While IsEmpty(ActiveCell) = False
lastYear = ActiveCell.Value
ActiveCell.Offset(1, 0).Select
Wend
ActiveCell.Value = lastYear + 1
Range("A1").Select 'Return to Cell A1
End Sub
QUESTIONS?