VBA coding for
Excel
CHELSEA DOHEMANN
Today We’re Going to Day 1
Cover
Morning Afternoon
Introduction to Macros VB Grammar
Recording Macros Inserting & Formatting Text
Editing Macros Sorting Data
VBA Interface Variables & Operators
Macro Security Duplicating Data
Debugging Generating Reports
Customizing Ribbon and Toolbars Various Properties, Objects and
Methods
Today We’re Going to Day 1
Cover
Morning Afternoon
Introduction to Macros VB Grammar
Recording Macros Inserting & Formatting Text
Editing Macros Sorting Data
VBA Interface Variables & Operators
Macro Security Duplicating Data
Debugging Generating Reports
Customizing Ribbon and Toolbars Various Properties, Objects and
Methods
Object-Oriented
Programming
Color
Purpos
e
Size
Object
Modelled like real time objects
Macros
Macro Options
The Macro Recorder
Personal Macro Workbook
Visual Basic Editor
Project
Code
Explorer
Window
Properties
Window
Immediate Window
Modules
Objects
Columns
Cells A1
Sheets Tables Charts
Rows
Hierarchy of Objects Application
Workbooks
Worksheet
s
Ranges Columns Rows
Properties
A1 .Color
$100
$1,000,000 .Value
Text
Text .Font
Methods
Copy
Clear
Contents
Column
Auto Fit
s
VBA Comments
“comment out” a block all at once
Macro Security Settings
Digital Certificates
Digital Signatures
The Debugging
Process Determine problem
Set up environment Back up Run code
with error
Execute code Retest to ensure
Reset Data line by line Fix code error error is fixed
to find the error
Debugging Tools
Toggle
Run Macro Exit Break-Mode
Breakpoint
Compile Step-Into
Intellisense Window
Method
s
Properti
es
Objects
Object Browser
The Range Object
Range (“A1”) . Value = “Hello”
Using the Range object
Range (“A1”) . Value = “Hello”
Range (“A1”) . Interior . Color = vbYellow
Range (“A1”) . Font . Color = vbRed
Different ways to express the same Range
Range(“C3”)
Range(“B2”).Range(“B2”)
Cells(3,3)
[C3]
Range(“A1”).Offset(2,2)
MyRange = “C3”
Range(MyRange)
Color Options in VBA
Theme Colors VB Colors
xlThemeColorLight1 vbBlack
xlThemeColorDark1 vbWhite
xlThemeColorDark2 vbRed
xlThemeColorlight2 vbLine
xlThemeColorAccent1 vbYellow
xlThemeColorAccent2 vbBlue
xlThemeColorAccent3 vbMagenta
xlThemeColorAccent4 vbCyan
xlThemeColorAccent5 Range (“A1”) . Font . Color =
xlThemeColorAccent6 vbRed
Range (“A1”) . Font . ThemeColor = xlThemeColorLight1
Color Options in VBA
RGB Colors Hexidecimal
Blue – ( 0 , 0 , 255 ) (Hex)
Yellow – ( 255 , 255 , 0 ) Blue – 16711680
Cyan – ( 0 , 255 , 255 ) Yellow – 65535
Magenta – ( 255 , 0 , 255 Cyan – 16776960
) Magenta – 16711935
Range (“A1”) . Font . Color =
RGB(1,1,1)
(Can’t have the # sign, which
people are used to seeing with
the hex code)
Range (“A1”) . Font . Color = 65535
The Selection Object
Selection . Value = “Hello”
The Value Property
Range(“A1”) . Value =
“Hello”
The ActiveSheet Object
ActiveSheet . Name =
“Sheet1”
The Name Property
ActiveSheet . Name =
“Sheet1”
Concatenation
&
The Select Method
Range(“B2”) Select
.
The CurrentRegion
Property
Range(“A1”) . CurrentRegion .
Select
Practice
Insert Headers
Format Headers, and Columns
Format Cell Interior of Lists
Variables
DATA STORAGE
Different Data Types
Text Number Boolean
≠ ≠
Common Data Types
Numbers Text
Decimal Double Integer Variant String Char
• 28 decimal • Gazillians • -2M – 2M • All • 2B • 0 - 65535
placeholders • 8 bytes • 2 bytes • 16-32 characters • 2 bytes
• 14 bytes bytes • Depends
Boolean / Byte
Misc
Date Object Range
Boolean Byte
• 1900- • Any • Any
• True / False • 0-255
9999 • 4-32 • 4-32
• 2 bytes • 1 byte • 8 bytes bytes bytes
Variables
Sunshine? Or Clouds?
Sunshin
Clouds
e
Sunshin
e
Stores a bit of Code Delivers that code to some kind of process
Stating Variables
NameofVariable
Variable Declaration: Data Type:
“Okay VBA, I’m making a variable” “This is going to be a number”
or “Text” or “Boolean”
Exercise: Create some Variables
String Double
Name: ExString Name: ExDouble
Data: “This is Dummy Data: 5.5
Text” MsgBox “Value is” &
Make A1’s value the example value
example text
Boolean
Integer Name: ExBoolean
Name: ExInteger ExBoolean = True
Data: 5.5 If ExBoolean = True then
MsgBox “Value is” & MsgBox “Boolean variables
example value are cool!”
(Math) Operators
+ - * /
< > = <>
Loops
TO REPEAT ACTIONS MULTIPLE TIMES
Open “For Next Loop” XLSM
The For Next Loop
To make an action repetitive (a specific number of repetitions)
Scenario:
We want to input the value “100” multiple times into some cells.
Strategy:
We’ll make a variable called “x” and use it to stand in for the numerical
value of each iteration of the loop.
The For Next Loop
First: Define your variable
Dim x as Integer
The For Next Loop
Next: Write the code that we want to repeat
Dim x as Integer
Range(x, 1).Value = 100
The For Next Loop
Next: Wrap the For-Next Loop around the code to repeat it
Dim x as Integer
For
Range(x, 1).Value = 100
Next
The For Next Loop
Next: enter the code to establish he number of times this should repeat
Dim x as Integer
For x = 1 - 10
Range(x, 1).Value = 100
Next
The For Next Loop
Finish: complete the Next statement, tell it to move to the next x
Dim x as Integer
For x = 1 - 10
Range(x, 1).Value = 100
Next x
The For Next Loop
Challenge! Try out the two other For Loop examples in this
workbook.
“For Next Loop” xlsm
Rehearse For Next Loop
Design a Variable
For Next Loop (For x = 1 to ………..)
Inside the Loop
Select Worksheet(x)
Start with A1
Select Current Region
Copy Content
Select Sheet to paste on
Select cell to start with
Insert offset function
Paste
End the Loop
For Next Loop Answer
Open “Do While Loop” XLSM
The Do While Loop
To repeat an action, until a specific criteria is met
Scenario:
We want to input the value “100” multiple time, until we reach Row 10.
Strategy:
We’ll make a variable called “x” and use it to stand in for the numerical
value of each iteration of the loop.
The Do While Loop
First: Define your variable
Dim x as Integer
The Do While Loop
Then: Define your starting value
Dim x as Integer
X = 1
The Do While Loop
Then: Write the code that you want to repeat
Dim x as Integer
x = 1
Cells(x, 1).Value = 100
The Do While Loop
Then: Surround the repeated code with a Do While Loop
Dim x as Integer
x = 1
Do While
Cells(x, 1).Value = 100
Loop
The Do While Loop
Then: code the criteria for stopping the loop
Dim x as Integer
x = 1
Do While x < 10
Cells(x, 1).Value = 100
Loop
The Do While Loop
Then: code the statement to count up after you’ve executed the repeatable code
Dim x as Integer
x = 1
Do While x < 10
Cells(x, 1).Value = 100
x = x + 1
Loop
The Do While Loop
Challenge! Try out the two other For Loop examples in this
workbook.
“Do While Loop” xlsm
The Count Property
The Offset Property
Moves our cell selection using
relative cell relationships
Navigates up or down Rows
Offset( 1 , 1 )
Navigates left or right across columns
The Offset Property
Positive Numbers = Down
Negative Numbers = Up
Offset( 1 , 1 )
Positive Numbers = Right
Negative Numbers = Left
The Offset Property
Offset(1, 1)
Offset(-1, -1)
The Copy Method
Selection.Copy
The Paste Method
ActiveSheet.Paste
The Columns Property
Columns(“B:B”).Select
The AutoFit Method
Doesn’t fit! Now it fits!
Columns(“B:C”).AutoFit
The Address Property
The Call Statement
We can have a Procedure run other macros using the “Call” statement
The Font Property
ActiveCell.Font.Name = “Verdana”
The End Property
ActiveCell.End(x1Down) ActiveCell.End(x1toRight)
Message Boxes
MsgBox options
MsgBox “Message”, vbOption, “Message Box Title”
vbYesNo vbMsgBoxHelpBut vbOKCancel vbOKOnly
ton
vbYesNoCancel vbRetryCancel
vbInformatio
n
Input Boxes
Type text here.
Input Boxes
Question Default Text
Name of Box
Constants
Declaring constants works a lot like declaring variables, EXCEPT the
value has to be defined at the same time.
Constant Declaration: Constant Value:
“Okay VBA, I’m making a constant” “The value of this constant is…”
The Code Continuation
Character _
To be safe, always precede it with a space
The vbCrLf Constant
Decision Structures
Code blocks that allow us to: Run a statement if a condition is
TRUE
…previous code….
Is the
YES Condition no
TRUE?
Perform actions for
TRUE Do nothing
Next code…
Decision Structures
Code blocks that allow us to: Run a statement if a condition is TRUE, and another if
FALSE
…previous code….
Is the
YES Condition NO
TRUE?
Perform actions for Perform actions for
TRUE FALSE
Next code…
Decision Structures
Code blocks that allow us to: Run a statement if a condition is
FALSE,
…previous code….
Is the
yes Condition NO
TRUE?
Perform actions for Perform actions for
TRUE FALSE
Next code…
The IF THEN Structure
If B4 is greater than 60
Enter “Pass” in C4
The IF THEN ELSE
Structure
If B4 is greater than 60
Enter “Pass” in C4
If B4 is LESS than 60
Enter “Fail” in C4
If Then Else Structures can get
looong…
Way too much typing.
The Select Case Structure
**Use & define a variable
Let’s look as cases for X
In this case
Do this
In this case
Do this
In this case
Do this
In every other case
Do this
Done
Select Case – Case Options
To check if a case is a Text To check if a case is a
value Number(s)
Case “Word” Case 1, 2
To check if a case is a number
To check if a case Compares
Range
Case 1 To 10 Case Is < 100
The Add Method
Worksheets.Add
The Add Method
Worksheets.Add Before:=Worksheets(3)
The Add Method
Worksheets.Add After:=Worksheets(1)
The Copy Method
Worksheets(2).Copy Before:=Worksheets(4)
Worksheets(2).Copy After:=Worksheets(2)
The Delete Method
Worksheets(2).Delete
The DateSerial Function
Range(“A1”).Value = DateSerial(2011, 11, 28)
Range(“A1”).Value = DateSerial(2011-1, 11-1, 28-1)
The Format Function (for Dates)
Note! This returns a text value, date’s serial number is lost
The Format Function (for Non-Dates, Main
Categories)
General Number
Standard
Currency
Percent
The Number Format
Option
Unlike the Format Function, this just changes the formatting of the number;
Maintains the serial number for the date
The Move Method
Worksheets(2).Move Before:=Worksheets(4)
Worksheets(2).Move After:=Worksheets(2)
The PrintPreview Method
Worksheet
Worksheet
object
object reference
reference
Previews
Previews allall the
the worksheets
worksheets
in
in the
the workbook
workbook Worksheets.PrintPreview
Previews
Previews the
the second
second worksheet
worksheet Worksheets(2).PrintPreview
in
in the
the workbook
workbook
Previews
Previews the
the worksheet
worksheet Worksheets(“SE Sales”).PrintPreview
named
named SE
SE Sales
Sales
The PrintOut Method
Worksheet
Worksheet
object
object reference
reference
Prints
Prints all
all the
the worksheets
worksheets
in
in the
the workbook
workbook Worksheets.PrintOut
Prints
Prints the
the second
second worksheet
worksheet
in
in the
the workbook
workbook
Worksheets(2).PrintOut
Prints
Prints the
the worksheet
worksheet
named
named SESE Sales
Sales
Worksheets(“SE Sales”).PrintOut
User-Defined Functions
Function
Function Name
Name
Optional
Optional variables
variables
Beginning
Beginning
statement
statement Public Function Pricelevel(amount, byr, eyr)
If byr < 1913 Or byr > 2003 Or eyr < 1913 or eyr > 2003 Then
PriceLevel = 0
Processing
Processing
code
code Else Result
Result placed
placed into
into aa variable
variable having
having the
the function
function name
name
PriceLevel = amount * CPI_idex(eyr) / CPI_idex(byr)
End If
Closing
Closing
statement
statement End Function
Arguments
Data
Data sent
sent from
from worksheet
worksheet
to
to function
function for
for processing
processing
Public Function PriceLevel(amount, byr, eyr)
Arguments
Arguments listed
listed within
within parentheses
parentheses
Declared Range Objects
Dim MyRange As Range
Range
Range object
object name
name
The Set Statement
Set MyRange = Range(“A2:E5”)
The Rows Property
Set MyRange = Range(“A2:E5”)
MyRange.Rows(3)
The Formula Property
Formula
Formula property
property attached
attached to
to
Range
Range object
object
MyRange.Formula = “=SUM(A1:C6)”
The Columns Property
Set MyRange = Range(“A2:E5”)
MyRange.Columns(3)
Format Function
General Number Displays a number without thousand separators.
Fixed
possibilities
Currency Displays thousand separators as well as two decimal places.
Displays at least one digit to the left of the decimal place and
two digits to the right of the decimal place.
Displays the thousand separators, at least one digit to the left of
Standard the decimal place, and two digits to the right of the decimal
place.
Displays a percent value - that is, a number multiplied by 100
Percent with a percent sign. Displays two digits to the right of the
decimal place.
Scientific Scientific notation.
Displays No if the number is 0. Displays Yes if the number is not
Yes/No
0.
Displays False if the number is 0. Displays True if the number is
True/False
not 0.
Displays Off if the number is 0. Displays On is the number is not
On/Off
0.
General Date Displays date based on your system settings
Long Date Displays date based on your system's long date setting
Medium Date Displays date based on your system's medium date setting
Short Date Displays date based on your system's short date setting
Long Time Displays time based on your system's long time setting
Time for a Break
We’ll resume class at 2:50pm