vba class level 1
DESCRIPTION
Level 1 of a class which I lead at AIMCo in training investment professionals in VBA programmingTRANSCRIPT
Visual Basic Applications (VBA)
Level I
By Ben Miu
What is Excel VBA?
• VBA is a MS Office based programming language modeled after Visual Basic 6.0
• Prior to VBA, automation in Excel was done with XLMMacros which lacked programming functionality
• Visual Basic evolved from BASIC, getting rid of the idea of structural programming
• Excel VBA is the end all of advanced Excel
Imagine …
• Many in AIMCo is doing manual tedious tasks of cutting and pasting spreadsheets
• Example: John is taking a file from a folder and creating a file folder then copying the file using Windows Explorer
• Example: Jim is manually drawing a line between two charts
• Example: Kim is manually cutting and pasting numbers from one spreadsheet to another
• Example: Simon is grabbing prices from a website on a daily basis and putting it into a spreadsheet
• What do all of these examples have in common?
Automation is the Answer
• VBA can copy files from a folder and put it into another folder. It can create files, delete directories
• VBA can draw lines between two charts and the code written can set business rules as to why you would do that
• VBA can cut and paste numbers without you even having to switch sheets
• VBA can access websites and grab information
Simply put, what can be imagined can be achieved with automation
Using the Macro Recorder
• Macro recorder is included in Excel. It is the most basic way of learning VBA and it’s where it all starts…
• Lab 1: Use the macro recorder to put the word “Ben” into Range A1. Examine the code, what do you see?
Advantages/Disadvantages of the Macro Recorder
Advantage:- Macro recorder has the ability to type code for you without you knowing ‘the code’- It can simplify your tasks if you are simply cutting and pasting the same cell everydayDisadvantage:- Lacks clear business logic abilities- Code is highly inefficient
The VBA Code Screen
• Alt-F11 opens up the code screen, or you can use the Developer Tab
• Macros may be disabled in Excel so you may need to tweak security settings, always save your files as .XLSM so you don’t lose your code
• Code is inserted into modules. Each time you use the recorder, a new module is created. Not necessarily the best approach
Code goes there
Recorder Code, before and after
After …
What happened?
• Macro recorder had to select each cell first and then used ambiguous activecell reference to change cell value
• The R1C1 doesn’t state anything about which cell you are changing and is not intuitive to people reading the code
• Code can be extremely long if you have to use the recorder for many entries
Why?
Workbooks(“Daily Risk.xlsm”).Sheets(“Sheet1”).Range(“A1”).Value = “Ben”
Workbooks Reference
Sheet Reference Range Reference
Value
Rewrite your lab using this syntax
The VBE Interface
Intermediates Window / Debug Window
Code inserted into a Subroutine
Modules hold code
Play and stop button
What is a variable?
• Variables store information into the computers memory for easy access
• Variables can contain text, numbers, dates, arrays, objects
• Example of creating a variableDim TotalAmount as Double
Choose a proper name for your variables
Types of Variables
• String – Text Only• Integer - -32768 to 32767 (Whole numbers only,
no decimals)• Long - -2,147,483,684 to 2,147,483,684(Whole
numbers only, no decimals)• Boolean – True or False• Double – Numbers with decimals• Any variables not declared with a dim statement
are assigned as Variant
Sample Code
Sub Test()
Dim TotalAmount as Double
TotalAmount = 100.00
Range(“A5”).Value = TotalAmount
End Sub ()
Declare variable
Assign variable
Procedure
If-Then-Else
• If-Then-Else is your most commonly used decision tree statement
• If Condition Then Code goes here
End If
If Condition ThenCode goes hereElseCode goes hereEnd If
If statements must always have a End If
Else statement executes code if condition is not met
Range vs. Cell
• Range(“A5”).Value = 100
• Cells(1,5).Value = 100
Both statements do the same thing. The Cells statement is useful if you know the row and column index number
String Concatenation
• You already know how to Dim a variable and assign a value to it
Dim SanaActivity as StringDim ActivityString as String
ActivityString = “Skiing”
SanaActivity = “Sana enjoys “ & Activitystring & “ very much”
Indenting your code and commenting your code
• Always important to indent your code• Use the ‘ to comment your code
Dim TotalAmount as DoubleTotalAmount = 100
If Range(“A5”).Value = 200 ThenRange(“A5”).Value = TotalAmountElseRange(“A5”).Value = “No”End If
‘Creates variablesDim TotalAmount as Double
‘Assigns variablesTotalAmount = 100
‘Assigns a proper value to the cellIf Range(“A5”).Value = 200 Then
Range(“A5”).Value = TotalAmountElse
Range(“A5”).Value = “No”End If
Bad Code
Good Code
Lab 2 – Writing your first programSub Test()
Dim CashAmount as Double
CashAmount = 100
If Range(“A1”).Value > 100 ThenMsgbox(“Less than 100”)
ElseIf Range(“A1”).Value < 100 ThenMsgbox(“Less than 100”)
ElseMsgbox(“Not a number”)
End If
End Sub
Try experimenting with theCashAmount variable by typing in:
CashAmount = (100 * 2) + 40
What happens if you type this in as the variable:
CashAmount = (100 * 2) + “JERRYYANG!”
For Next Loop• This type of loop is if you know how many iterations you need to go through• Counter variables are used to assist the For Next Loop in moving between
cells• What is a counter variable?• Counter variable is a variable which does nothing other than keep count
and holds a simple integer value• Example:
Dim I as Integer
I = 0
To increment a counter variable (not used in for next loops generally), you commonly use this notation I = I + 1
For Next Loop continued…
• Dim I as Integer I = 0
For I = 1 to 5Range(“A” & i).value = “Jerry”
Next
What does this code do?
Do While Loop
• This kind of loop is used if you are not sure how many iterations you need to go through
• It is used ‘while’ a condition is met. Once the condition is met, the loop kicks you out
• Commonly used is with a While/Wend loop moving through ranges/cells
Do While Loop Example
Dim I as Integeri = 1
Do While Range(“A” & I ).value = “Jerry”I = I + 1Msgbox(“Yang”)
Wend
Do Loop – Beware this one
• This loop is used if you do not want to put a condition into the loop but want to put a “Exit Do” into the Do Loop
• This loop is useful if you want a If-Then-Else statement to handle the exiting of the loop
• Beware this loop, as this one causes a infinite loop where there is no ending (unless you ESC out of the program)
Do Loop Example
Dim TotalAmount as DoubleTotalAmount = 100
DoMsgbox(“TotalAmount”)
Loop
Do you see a problem with this code?
Do Loop Proper Example
Dim TotalAmount as DoubleDim I as Integer
TotalAmount = 100I = 0
DoI = I + 1Msgbox(“OK”)If I = 5 Then Exit Do
Loop
New form of If statementDoesn’t require End If
Exit Do statement throws you out of the loop
Lab 3 – Lots of LoopsDim TotalAmount as DoubleDim I as IntegerDim SecretaryNameSecretaryName = “Sana Farrukh”TotalAmount = 100I = 0
Do While TotalAmount <> 0I = I + 1TotalAmount = TotalAmount - 1Range(“A” & i).Value = TotalAmount
Loop
For j = 100 to 1 Step -1Range(“B” & j).Value = SecretaryName
Next
I = 100
DoRange(“C” & i).Value = “Our Secretary name is “ & SecretaryNameI = I – 1If I = 1 Then Exit Do
Loop
Debugging and Error Trapping
• As you can see, if you mistype something, you get a Debug error message which will highlight the code that went bad
Ie.
Dim SecretaryName as StringSecretaryName = 33Error is Type Mismatch
Debugging and Error Trapping 2
• Putting stops in code. Click on the line to the left
Code Stops Here
Using Debug.Print
• Sometimes you want to find out the value of a variable as you run through your code
• You don’t necessarily want to stop your code as with the prior example of the RED dot
• So you use the Debug.Print to put the contents of a variable in the debug window
• Useful in loops where you want to see what the loop is doing to a variable or cell
Debug.Print statement insertedCan you think of where the value of “a.value”Will go to?
Perhaps here?
Do you see a problem with this if you are trying to deal with all AIMCo Employees?
Dim AIMCOEmployeeLeo as StringDim AIMCO EmployeeJagdeep as StringDim AIMCO EmployeeRyan as String
AIMCOEmployeeLeo = “Leo”AIMCOEmployeeJagdeep = “Jagdeep”AIMCOEmployeeRyan = “Ryan”
Perhaps an array helps
Dim AIMCOEmployee(250) as String
AIMCOEmployee(1) = “Leo”AIMCOEmployee(2) = “Jagdeep”AIMCOEmployee(3) = “Ryan”
Arrays
• An array is a variable which contain several values in itself and centralizes data contained
• To create an array you;Dim AIMCOEmployees(250) as String
AIMCOEmployees(1) = “Sana”AIMCOEmployees(2) = “Grant”AIMCOEmployees(3) = “Ryan”
And so on…
Lab 4• Put the following code into Excel VBA. What happens?
Dim RiskEmployees(3) as StringDim I as IntegerDim j as IntegerI = 0J = 0RiskEmployees(1) = “Ryan”RiskEmployees(2) = “Grant”RiskEmployees(3) = “John”
For I = 1 to 10Range(“A” & i).SelectFor j = 1 to 3
If Range(“A” & i).Value = RiskEmployees(j) Then Msgbox(“Great”)Next
Next
Nested loop. Wow!
Summary
• Macro Recorder• Creating Variables• If Then Else Loops• Do While Loops• Do Loops• Debugging and error trapping• Arrays
Thanks