2. 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
3. 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?
4. 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
6. 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?
7. 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 everyday
Disadvantage:
- Lacks clear business logic abilities
- Code is highly inefficient
8. 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
12. 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
14. Play and stop
button The VBE Interface
Code inserted into a Subroutine
Modules hold code
Intermediates Window / Debug Window
15. 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 variable
Dim TotalAmount as Double
Choose a proper name for your variables
16. 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
17. Sample Code
Sub Test() Declare variable
Dim TotalAmount as Double
Assign variable
TotalAmount = 100.00
Range(“A5”).Value = TotalAmount Procedure
End Sub ()
18. If-Then-Else
• If-Then-Else is your most commonly used
decision tree statement
• If Condition Then
If statements must
Code goes here always have a End If
End If
If Condition Then
Code goes here Else statement
executes code if
Else condition is not met
Code goes here
End If
19. 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
20. String Concatenation
• You already know how to Dim a variable and
assign a value to it
Dim SanaActivity as String
Dim ActivityString as String
ActivityString = “Skiing”
SanaActivity = “Sana enjoys “ & Activitystring & “
very much”
21. Indenting your code and commenting
your code
• Always important to indent your code
• Use the ‘ to comment your code
Good Code
Dim TotalAmount as Double ‘Creates variables
TotalAmount = 100 Dim TotalAmount as Double
If Range(“A5”).Value = 200 Then ‘Assigns variables
Range(“A5”).Value = TotalAmount TotalAmount = 100
Else
Range(“A5”).Value = “No” ‘Assigns a proper value to the cell
End If If Range(“A5”).Value = 200 Then
Range(“A5”).Value = TotalAmount
Else
Bad Code
Range(“A5”).Value = “No”
End If
22. Lab 2 – Writing your first program
Sub Test() Try experimenting with the
CashAmount variable by
Dim CashAmount as Double typing in:
CashAmount = 100 CashAmount = (100 * 2) + 40
If Range(“A1”).Value > 100 Then
Msgbox(“Less than 100”)
ElseIf Range(“A1”).Value < 100 Then
Msgbox(“Less than 100”)
Else
Msgbox(“Not a number”)
End If
What happens if you type this
End Sub
in as the variable:
CashAmount = (100 * 2) +
“JERRYYANG!”
23. 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
24. For Next Loop continued…
• Dim I as Integer What does this code do?
I=0
For I = 1 to 5
Range(“A” & i).value = “Jerry”
Next
25. 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
26. Do While Loop Example
Dim I as Integer
i=1
Do While Range(“A” & I ).value = “Jerry”
I=I+1
Msgbox(“Yang”)
Wend
27. 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)
28. Do Loop Example
Dim TotalAmount as Double Do you see a problem
with this code?
TotalAmount = 100
Do
Msgbox(“TotalAmount”)
Loop
29. Do Loop Proper Example
Dim TotalAmount as Double
Dim I as Integer
TotalAmount = 100
I=0
Do
I=I+1
Msgbox(“OK”) New form of If statement
Doesn’t require End If
If I = 5 Then Exit Do
Loop
Exit Do statement throws you out of the loop
30. Lab 3 – Lots of Loops
Dim TotalAmount as Double
Dim I as Integer
Dim SecretaryName
SecretaryName = “Sana Farrukh”
TotalAmount = 100
I=0
Do While TotalAmount <> 0
I=I+1
TotalAmount = TotalAmount - 1
Range(“A” & i).Value = TotalAmount
Loop
For j = 100 to 1 Step -1
Range(“B” & j).Value = SecretaryName
Next
I = 100
Do
Range(“C” & i).Value = “Our Secretary name is “ & SecretaryName
I=I–1
If I = 1 Then Exit Do
Loop
31. 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 String
SecretaryName = 33
Error is Type Mismatch
32. Debugging and Error Trapping 2
• Putting stops in code. Click on the line to the
left
34. 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
36. Do you see a problem with this if you
are trying to deal with all AIMCo
Employees?
Dim AIMCOEmployeeLeo as String
Dim AIMCO EmployeeJagdeep as String
Dim AIMCO EmployeeRyan as String
AIMCOEmployeeLeo = “Leo”
AIMCOEmployeeJagdeep = “Jagdeep”
AIMCOEmployeeRyan = “Ryan”
37. Perhaps an array helps
Dim AIMCOEmployee(250) as String
AIMCOEmployee(1) = “Leo”
AIMCOEmployee(2) = “Jagdeep”
AIMCOEmployee(3) = “Ryan”
38. 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…
39. Lab 4
• Put the following code into Excel VBA. What happens?
Dim RiskEmployees(3) as String
Dim I as Integer
Dim j as Integer Nested loop. Wow!
I=0
J=0
RiskEmployees(1) = “Ryan”
RiskEmployees(2) = “Grant”
RiskEmployees(3) = “John”
For I = 1 to 10
Range(“A” & i).Select
For j = 1 to 3
If Range(“A” & i).Value = RiskEmployees(j) Then Msgbox(“Great”)
Next
Next
40. Summary
• Macro Recorder
• Creating Variables
• If Then Else Loops
• Do While Loops
• Do Loops
• Debugging and error trapping
• Arrays