VBA CheatSheet


 


Basic Programming Operations

OperationCode
Declare a variableDim myVar As String
Set the value of a variablemyVar = “some value”
Set the value of an object variableSet myObj = Range(“B2:C3”)
Gather user inputuserInput = InputBox(“What’s your favorite color?”)
Print a message to the screenMsgBox(“You shall not pass!”)
Execute a macro from within another macroCall myMacro
Use a built-in worksheet function in a macroApplication.WorksheetFunction.CountA(“A:A”)
Comment out a line of code - note the apostrophe (‘)‘VBA will ignore me!

Basic Operations on Data

OperationCode
AdditionimFour = 2 + 2
SubtractionimZero = 2 - 2
MultiplicationimAlsoFour  = 2 * 2
Division (uses “/” operator)MsgBox(10 / 3) ‘returns 3.333333
Integer Division (uses “\” operator)MsgBox(10 \ 3) ‘returns 3
ConcatenationhelloWorld = “Hello” & “world”

Data Types

Data TypeDescriptionExample
IntegerWhole number between -32,768 and 32,76711
LongWhole numbers between -2,147,483,648 and 2,147,483,6471,234,567
SingleDecimal number with seven digits of precision3.141593
DoubleDecimal number with fifteen digits of precision3.14159265358979
DateDate values3/5/2021
StringText data“Hello world”
BooleanLogical true/false valuesFalse
RangeRange object in ExcelSet myRange = Range(“A1”)
WorksheetWorksheet object in ExcelSet mySheet = Sheets(“Sheet 1”)
WorkbookWorksheet object in ExcelSet myWorkbook = Workbooks(1)
VariantUnspecified data typemyVariant = “Anything goes!”

Logical/Comparison Operators

OperatorSymbolExample
Equals=5 = 5
Not Equals<>5 <> 55
Greater than>2 > 1
Greater than or equal to>=2 >= 2
Less than<4 < 5
Less than or equal to<=4 <= 5
AndAnd(5 = 5) And (5 <> 55) = True
(5 = 5) And (5 = 55) = False
(5 <> 5) And (5 = 55) = False
OrOr(5 = 5) Or (5 <> 55) = True
(5 = 5) Or (5 = 55) = True
(5 <> 5) Or (5 = 55) = False
NotNotNot (5 = 5) = False
Not (5 = 55) = True

If Statements

TypeExample ScenarioVBA Code
Simple If statementIf the value stored in the variable “val” is greater than 1,000, print the text “Large”.
Otherwise, do nothing.
If val > 1000 Then:
MsgBox(“Large”)
End If
If-Else statementIf the value stored in the variable “val” is greater than 1,000, print the text “Large”.
Otherwise, print the text “Small”.
If val > 1000 Then: MsgBox(“Large”)
Else: MsgBox(“Small”)
End If
If-ElseIf-Else statementIf the value stored in the variable “val” is greater than 1,000, print the text “Large”.
If the value stored in the variable “val” is between 200 and 1,000, print the text “Medium”. >
Otherwise, print the text “Small”.
If val > 1000 Then: MsgBox(“Large”)
Else If val >= 200 Then: MsgBox(“Medium”)
Else: MsgBox(“Small”)
End If

Loops

TypeExample ScenarioVBA Code
Do LoopPrint the first 5 integers to the screenDim counter As Integer
counter = 1
Do
If counter > 5 Then
Exit Do
End If
MsgBox (counter)
counter = counter + 1
Loop
Do While LoopPrint the first 5 integers to the screenDim counter As Integer
counter = 1 
Do While counter <= 5
MsgBox (counter)
counter = counter + 1
Loop
Do Until LoopPrint the first 5 integers to the screenDim counter As Integer
counter = 1
Do Until counter > 5
MsgBox (counter)
counter = counter + 1
Loop
For Next LoopPrint the first 5 integers to the screenDim counter As Integer 
For counter = 1 To 5
MsgBox (counter)
Next counter
For Each LoopPrint the values in cells A1 through A5 to the screenDim cell As Range
For Each cell In Range("A1:A5") 
MsgBox (cell.Value)
Next cell

Arrays

Example ScenarioVBA Code
Create an empty array with 5 integer elements and a 0-based indexDim myArr(5) As Integer
Set the value at the 3rd position of an array with a 0-based indexDim myArr(5) As Integer
myArr(2) = 3
Print the 3rd element of an array with a 0-based indexDim myArr(5)
myArr(2) = 3
MsgBox(myArr(2))
Create an empty 2-dimensional array with 3 rows and 2 columns, that can accommodate multiple data typesDim myArr(2, 1) As Variant
Set the values of a 3x2 arrayDim myArr(2, 1) As Variant
myArr(0,0) = “one”
myArr(0,1) = 1
myArr(1,0) = “two”
myArr(1,1) = 2
myArr(2,0) = “three”
myArr(2,1) = 3
Print the maximum index (upper bound) of an arrayDim myArr(5) As String
MsgBox(UBound(myArr))
Print all the elements of an array using a For Next LoopDim myArr(2) As Variant
myArr(0) = "one"
myArr(1) = 2
myArr(2) = "three"

Dim counter As Integer
For counter = 0 To UBound(myArr)
MsgBox (myArr(counter))
Next counter
Transfer data from cells A1 through A5 to an arrayDim myArr() As Variant
myArr = Range("A1:A5").Value
Transfer data from a 3-element array to an Excel rangeDim myArr(2) As Variant
myArr(0) = "one"
myArr(1) = 2
myArr(2) = "three"
Range("A1:C1") = myArr
Transfer data from a 3-element array to a vertical Excel rangeDim myArr(2) As Variant
myArr(0) = "one"
myArr(1) = 2
myArr(2) = "three"

Range("A1:A3") = Application.WorksheetFunction.Transpose(myArr)
Use the SPLIT function to convert a text string into an array of wordsDim textStr As String
Dim splitStr() As String
textStr = "I am a list of words"
splitStr() = SPLIT(textStr)
Use the JOIN function to combine an array of values into a single string, with those values separated by spacesDim myArr(5) As Variant
Dim combinedStr As String
myArr(0) = "I"
myArr(1) = “am”
myArr(2) = "a"
myArr(3) = "list"
myArr(4) = "of"
myArr(5) = "words"
combinedStr = JOIN(myArr, “ ”)

The With Construct

Example ScenarioVBA Code (without using With)VBA Code (using With)
Format cell A1 as follows: Bold, Italic, Font-style: Roboto, Font-size: 14Range("A1").Font.Bold = True
Range("A1").Font.Italic = True
Range("A1").Font.Name = "Roboto"
Range("A1").Font.Size = 14
With Range("A1").Font .Bold = True
.Italic = True
.Name = "Roboto"
.Size = 14
End With

Working With Ranges

Example ScenarioVBA Code
Target a single cell using a hard-coded referenceRange(“A1”)
Target multiple cells using a hard-coded referenceRange(“A1:C3”)
Print the value of a cell using a hard-coded referenceMsgBox(Range(“A1”).Value)
Set the value of a cell using a hard-coded referenceRange(“A1”).Value = 11
Print the value of the active cellMsgBox(ActiveCell.Value)
Set the value of the active cellActiveCell.Value = 22
Print the value of the cell 1 row below, and 2 columns to the right, of the active cellMsgBox(ActiveCell.Offset(1,2))
Set the value of the cell 1 row above, and 2 columns to the left, of the active cellActiveCell.Offset(-1,-2).Value = “I’m upset that I’ve been offset!”
Use the Cells property to print the value of cell A1MsgBox(Cells(1,1))
Use the Cells property to set the value of cell D3Cells(3,4).Value = “Row 3, column 4”
Use the Cells property within a For Next loop to print the values of the first 5 cells in column ADim counter As Integer
For counter = 1 To 5
MsgBox (Cells(counter, 1))
Next counter
Use the Cells property within a nested For Next loop to print the values of all the cells in a 2-dimensional selection (that is, the cells currently selected by the user)Dim a As Integer
Dim b As Integer

For a = 1 To Selection.Rows.Count
For b = 1 To
Selection.Columns.Count 
MsgBox (Selection.Cells(a, b))
Next b
Next a
Select the last cell with data in a column of values starting in cell A1Range("A1").End(xlDown).Select
Select all the values in a column of data starting in cell A1Range(Range("A1"), Range("A1").End(xlDown)).Select

Working With Worksheets

Example ScenarioVBA Code
Activate a sheet by referencing its nameSheets(“Sheet 1”).Activate
Activate a sheet by referencing its indexSheets(1).Activate
Print the name of the active worksheetMsgBox(ActiveSheet.Name)
Add a new worksheetSheets.Add
Add a new worksheet and specify its nameSheets.Add.Name = “My New Sheet”
Delete a worksheetSheets(“My New Sheet”).Delete
Hide a worksheetSheets(2).visible = False
Unhide a worksheetSheets(2).visible = True
Loop through all sheets in a workbookDim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets 
MsgBox (ws.Name)
Next ws

Working With Workbooks

Example ScenarioVBA Code
Activate a workbook by referencing its nameWorkbooks(“My Workbook”).Activate
Activate the first workbook that was opened, among all open workbooksWorkbooks(1).Activate
Activate the last workbook that was opened, among all open workbooksWorkbooks(Workbooks.Count).Activate
Print the name of the active workbookMsgBox(ActiveWorkbook.Name)
Print the name of this workbook (the one containing the VBA code)MsgBox(ThisWorkbook.Name)
Add a new workbookWorkbooks.Add
Open a workbookWorkbooks.Open(“C:\My Workbook.xlsx”)
Save a workbookWorkbooks(“My Workbook”).Save
Close a workbook and save changesWorkbooks(“My Workbook”).Close SaveChanges:=True
Close a workbook without saving changesWorkbooks(“My Workbook”).Close SaveChanges:=False
Loop through all open workbooksDim wb As Workbook
For Each wb In Application.Workbooks
MsgBox (wb.Name)
Next wb

Useful Keyboard Shortcuts

Press thisTo do this
Alt+F11Toggle between the VBA editor and the Excel window
F2Open the Object browser
F4Open the Properties window
F5Runs the current procedure (or resumes running it if it has been paused)
F8Starts “debug mode”, in which one line of code is executed at a time
Ctrl + BreakHalts the currently running procedure
Ctrl+JList the properties and methods for the selected object

No comments:

Post a Comment