0% found this document useful (0 votes)
6 views23 pages

VBA Cheat Sheet

The VBA Cheat Sheet provides a quick reference guide for key functions and concepts in Visual Basic for Applications, aimed at developers, data scientists, and analysts. It covers basic programming operations, data types, logical operators, control structures, and working with Excel objects like ranges, worksheets, and workbooks. Additionally, it offers resources for learning VBA through a course and includes useful keyboard shortcuts for the VBA editor.

Uploaded by

OusmaneKeita
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views23 pages

VBA Cheat Sheet

The VBA Cheat Sheet provides a quick reference guide for key functions and concepts in Visual Basic for Applications, aimed at developers, data scientists, and analysts. It covers basic programming operations, data types, logical operators, control structures, and working with Excel objects like ranges, worksheets, and workbooks. Additionally, it offers resources for learning VBA through a course and includes useful keyboard shortcuts for the VBA editor.

Uploaded by

OusmaneKeita
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

VBA Cheat Sheet

We created this Excel VBA Cheat Sheet initially for students


of our VBA (Visual Basic for Applications) Programming
Course. But we're now sharing it with any and all
Developers, Data Scientists, and Data Analysts that want to
learn and remember some of the key functions and
concepts of VBA and have a quick reference guide to the
basics of Visual Basic for Applications.

Want to download a PDF version of


this VBA Cheat Sheet?
Enter your email below and we'll send it to you 👇

Send Me The PDF


Unsubscribe anytime.

If you’ve stumbled across this cheatsheet and are just


starting to learn VBA, you've made a great choice!

VBA was created by Microsoft and is the the programming


language that lives within Excel and the Microsoft Office
suite of products. This has made it very popular with
companies solving analytics challenges and is a great
language to learn if you're interested in becoming a
Business Intelligence Analyst or Data Scientist.

However, if you're stuck in an endless cycle of YouTube


tutorials and want to start building real world projects,
become a professional developer, have fun and actually get
hired, then come join the Zero To Mastery Academy.
You'll learn VBA from actual industry professionals
alongside thousands of students in our private Discord
community.
You'll not only learn to become a top 10% VBA Programmer
and Data Analyst by learning advanced topics most courses
don't cover. You'll also build VBA projects, including a
complete data management system with a sleek user
interface that you can use to add to your portfolio and wow
employers!

Just want the cheatsheet? No problem! Please enjoy and


if you'd like to submit any suggestions, feel free to email us
at support@zerotomastery.io

Contents

Basic Programming Operations

Basic Operations on Data

Data Types

Logical/Comparison Operators

If Statements

Loops

Arrays

The With Construct


Working With Ranges

Working With Worksheets

Working With Workbooks

Useful Keyboard Shortcuts

Basic Programming
Operations

Operation Code

Declare a variable Dim myVar As String

Set the value of a variable myVar = “some value”

Set the value of an object variable Set myObj = Range(“B2:C3”)

userInput = InputBox(“What’s your favorite


Gather user input
color?”)

Print a message to the screen MsgBox(“You shall not pass!”)

Execute a macro from within another


Call myMacro
macro
Operation Code

Use a built-in worksheet function in a


Application.WorksheetFunction.CountA(“A:A”)
macro

Comment out a line of code - note the


‘VBA will ignore me!
apostrophe (‘)

Basic Operations on Data

Operation Code

Addition imFour = 2 + 2

Subtraction imZero = 2 - 2

Multiplication imAlsoFour = 2 * 2

Division (uses “/” operator) MsgBox(10 / 3) ‘returns 3.333333

Integer Division (uses “\” operator) MsgBox(10 \ 3) ‘returns 3

Concatenation helloWorld = “Hello” & “world”

Data Types
Data
Description Example
Type

Integer Whole number between -32,768 and 32,767 11

Whole numbers between -2,147,483,648 and


Long 1,234,567
2,147,483,647

Decimal number with seven digits of


Single 3.141593
precision

Decimal number with fifteen digits of


Double 3.14159265358979
precision

Date Date values 3/5/2021

String Text data “Hello world”

Boolean Logical true/false values False

Range Range object in Excel Set myRange = Range(“A1”)

Set mySheet = Sheets(“Sheet


Worksheet Worksheet object in Excel
1”)

Set myWorkbook =
Workbook Worksheet object in Excel
Workbooks(1)

myVariant = “Anything
Variant Unspecified data type
goes!”
Logical/Comparison
Operators

Symbo
Operator Example
l

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

And And (5 = 5) And (5 <> 55) = True

(5 = 5) And (5 = 55) = False

(5 <> 5) And (5 = 55) = False

Or Or (5 = 5) Or (5 <> 55) = True

(5 = 5) Or (5 = 55) = True

(5 <> 5) Or (5 = 55) = False

Not Not Not (5 = 5) = False


Symbo
Operator Example
l

Not (5 = 55) = True

If Statements

Type Example Scenario VBA Code

If the value stored in the variable “val” is If val > 1000 Then:
Simple If
greater than 1,000, print the text “Large”. MsgBox(“Large”)
statement
Otherwise, do nothing. End If

If val > 1000 Then:


If the value stored in the variable “val” is
If-Else MsgBox(“Large”)
greater than 1,000, print the text “Large”.
statement Else: MsgBox(“Small”)
Otherwise, print the text “Small”.
End If

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

Loops
Type Example Scenario VBA Code

Dim counter As Integer


counter = 1
Do
If counter > 5 Then
Do Loop Print the first 5 integers to the screen Exit Do
End If
MsgBox (counter)
counter = counter + 1
Loop

Dim counter As Integer


counter = 1
Do While Do While counter <= 5
Print the first 5 integers to the screen
Loop MsgBox (counter)
counter = counter + 1
Loop

Dim counter As Integer


counter = 1
Do Until Do Until counter > 5
Print the first 5 integers to the screen
Loop MsgBox (counter)
counter = counter + 1
Loop

Dim counter As Integer


For Next For counter = 1 To 5
Print the first 5 integers to the screen
Loop MsgBox (counter)
Next counter

Dim cell As Range


For Each cell In
For Each Print the values in cells A1 through A5 to
Range("A1:A5")
Loop the screen
MsgBox (cell.Value)
Next cell

Arrays
Example Scenario VBA Code

Create an empty array with 5


integer elements and a 0-based Dim myArr(5) As Integer
index

Set the value at the 3rd position of Dim myArr(5) As Integer


an array with a 0-based index myArr(2) = 3

Dim myArr(5)
Print the 3rd element of an array
myArr(2) = 3
with a 0-based index
MsgBox(myArr(2))

Create an empty 2-dimensional


array with 3 rows and 2 columns,
Dim myArr(2, 1) As Variant
that can accommodate multiple
data types

Dim myArr(2, 1) As Variant


myArr(0,0) = “one”
myArr(0,1) = 1
Set the values of a 3x2 array myArr(1,0) = “two”
myArr(1,1) = 2
myArr(2,0) = “three”
myArr(2,1) = 3

Print the maximum index (upper Dim myArr(5) As String


bound) of an array MsgBox(UBound(myArr))

Dim myArr(2) As Variant


myArr(0) = "one"
myArr(1) = 2
myArr(2) = "three"
Print all the elements of an array
using a For Next Loop
Dim counter As Integer
For counter = 0 To UBound(myArr)
MsgBox (myArr(counter))
Next counter

Transfer data from cells A1 Dim myArr() As Variant


through A5 to an array myArr = Range("A1:A5").Value
Example Scenario VBA Code

Dim myArr(2) As Variant


myArr(0) = "one"
Transfer data from a 3-element
myArr(1) = 2
array to an Excel range
myArr(2) = "three"
Range("A1:C1") = myArr

Dim myArr(2) As Variant


myArr(0) = "one"
myArr(1) = 2
Transfer data from a 3-element
myArr(2) = "three"
array to a vertical Excel range
Range("A1:A3") =
Application.WorksheetFunction.Transpose(myArr)

Dim textStr As String


Use the SPLIT function to
Dim splitStr() As String
convert a text string into an array
textStr = "I am a list of words"
of words
splitStr() = SPLIT(textStr)

Dim myArr(5) As Variant


Dim combinedStr As String
myArr(0) = "I"
Use the JOIN function to combine
myArr(1) = “am”
an array of values into a single
myArr(2) = "a"
string, with those values separated
myArr(3) = "list"
by spaces
myArr(4) = "of"
myArr(5) = "words"
combinedStr = JOIN(myArr, “ ”)

The With Construct

VBA Code (without using VBA Code (using


Example Scenario
With) With)

Format cell A1 as follows: Bold, Range("A1").Font.Bold = With


VBA Code (without using VBA Code (using
Example Scenario
With) With)

True Range("A1").Font .Bold


Range("A1").Font.Italic = = True
Italic, Font-style: Roboto, Font- True .Italic = True
size: 14 Range("A1").Font.Name = .Name = "Roboto"
"Roboto" .Size = 14
Range("A1").Font.Size = 14 End With

Working With Ranges

Example Scenario VBA Code

Target a single cell using a hard-coded


Range(“A1”)
reference

Target multiple cells using a hard-coded


Range(“A1:C3”)
reference

Print the value of a cell using a hard-coded


MsgBox(Range(“A1”).Value)
reference

Set the value of a cell using a hard-coded


Range(“A1”).Value = 11
reference

Print the value of the active cell MsgBox(ActiveCell.Value)

Set the value of the active cell ActiveCell.Value = 22

Print the value of the cell 1 row below, and 2


MsgBox(ActiveCell.Offset(1,2))
columns to the right, of the active cell
Example Scenario VBA Code

Set the value of the cell 1 row above, and 2 ActiveCell.Offset(-1,-2).Value = “I’m
columns to the left, of the active cell upset that I’ve been offset!”

Use the Cells property to print the value of cell


MsgBox(Cells(1,1))
A1

Use the Cells property to set the value of cell


Cells(3,4).Value = “Row 3, column 4”
D3

Dim counter As Integer


Use the Cells property within a For Next loop
For counter = 1 To 5
to print the values of the first 5 cells in column
MsgBox (Cells(counter, 1))
A
Next counter

Dim a As Integer
Dim b As Integer
Use the Cells property within a nested For
For a = 1 To Selection.Rows.Count
Next loop to print the values of all the cells in
For b = 1 To
a 2-dimensional selection (that is, the cells
Selection.Columns.Count
currently selected by the user)
MsgBox (Selection.Cells(a, b))
Next b
Next a

Select the last cell with data in a column of


Range("A1").End(xlDown).Select
values starting in cell A1

Select all the values in a column of data Range(Range("A1"),


starting in cell A1 Range("A1").End(xlDown)).Select

Working With Worksheets


Example Scenario VBA Code

Activate a sheet by referencing its name Sheets(“Sheet 1”).Activate

Activate a sheet by referencing its index Sheets(1).Activate

Print the name of the active worksheet MsgBox(ActiveSheet.Name)

Add a new worksheet Sheets.Add

Add a new worksheet and specify its name Sheets.Add.Name = “My New Sheet”

Delete a worksheet Sheets(“My New Sheet”).Delete

Hide a worksheet Sheets(2).visible = False

Unhide a worksheet Sheets(2).visible = True

Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Loop through all sheets in a workbook
MsgBox (ws.Name)
Next ws

Working With Workbooks

Example Scenario VBA Code

Activate a workbook by referencing its


Workbooks(“My Workbook”).Activate
name

Activate the first workbook that was Workbooks(1).Activate


Example Scenario VBA Code

opened, among all open workbooks

Activate the last workbook that was


Workbooks(Workbooks.Count).Activate
opened, among all open workbooks

Print the name of the active workbook MsgBox(ActiveWorkbook.Name)

Print the name of this workbook (the


MsgBox(ThisWorkbook.Name)
one containing the VBA code)

Add a new workbook Workbooks.Add

Open a workbook Workbooks.Open(“C:\My Workbook.xlsx”)

Save a workbook Workbooks(“My Workbook”).Save

Workbooks(“My Workbook”).Close
Close a workbook and save changes
SaveChanges:=True

Close a workbook without saving Workbooks(“My Workbook”).Close


changes SaveChanges:=False

Dim wb As Workbook
For Each wb In Application.Workbooks
Loop through all open workbooks
MsgBox (wb.Name)
Next wb

Useful Keyboard
Shortcuts
Press this To do this

Alt+F11 Toggle between the VBA editor and the Excel window

F2 Open the Object browser

F4 Open the Properties window

F5 Runs the current procedure (or resumes running it if it has been paused)

F8 Starts “debug mode”, in which one line of code is executed at a time

Ctrl +
Halts the currently running procedure
Break

Ctrl+J List the properties and methods for the selected object

xample

This example turns off AutoSave and notifies the user that the workbook is
not being automatically saved.

VBCopy
Sub UseAutoSaveOn()
ActiveWorkbook.AutoSaveOn = False
MsgBox "This workbook is being saved automatically: " &
ActiveWorkbook.AutoSaveOn
End Sub

Application.WorkbookBeforeSave
event (Excel)
 09/13/2021

Occurs before any open workbook is saved.

Note

In Office 365, Excel supports AutoSave, which enables the user's edits to
be saved automatically and continuously. For more information, see How
AutoSave impacts add-ins and macros to ensure that running code in
response to the WorkbookBeforeSave event functions as intended when
AutoSave is enabled.

Syntax
expression.WorkbookBeforeSave (Wb, SaveAsUI, Cancel)

expression A variable that represents an Application object.

Parameters
Expand table
Name Required/Optional Data type Description
Wb Required Workboo The workbook.
k
SaveAsU Required Boolean True if the Save As dialog box will be displayed
I due to changes made that need to be saved in the
workbook.
Cancel Required Boolean False when the event occurs. If the event
procedure sets this argument to True, the
workbook isn't saved when the procedure is
finished.

Return value
Nothing

Example
This example prompts the user for a yes or no response before saving any
workbook.

VBCopy
Private Sub App_WorkbookBeforeSave(ByVal Wb As Workbook, _
ByVal SaveAsUI As Boolean, Cancel as Boolean)
a = MsgBox("Do you really want to save the workbook?", vbYesNo)
If a = vbNo Then Cancel = True
End Sub

Support and feedback

Have questions or feedback about Office VBA or this documentation?


Please see Office VBA support and feedback for guidance about the ways
you can receive support and provide feedback.
Application.WorkbookDeactivate
event (Excel)
 09/13/2021

Occurs when any open workbook is deactivated.

Syntax
expression.WorkbookDeactivate (Wb)

expression A variable that represents an Application object.

Parameters
Expand table
Name Required/Optional Data type Description
Wb Required Workbook The workbook.

Return value
Nothing

Example
This example arranges all open windows when a workbook is deactivated.

VBCopy
Private Sub App_WorkbookDeactivate(ByVal Wb As Workbook)
Application.Windows.Arrange xlArrangeStyleTiled
End Sub

Support and feedback

Have questions or feedback about Office VBA or this documentation?


Please see Office VBA support and feedback for guidance about the ways
you can receive support and provide feedback.

Application.WorkbookNewChart event (Excel)

 09/13/2021

Occurs when a new chart is created in any open workbook.


Syntax

expression.WorkbookNewChart (Wb, Ch)

expression A variable that represents an Application object.

Parameters

Expand table

Name Required/Optional Data type Description

Wb Required Workbook The workbook.

Ch Required Chart The new chart.

Return value

Nothing

Remarks

The WorkbookNewChart event occurs when a new chart is inserted or pasted on a


worksheet, a chart sheet, or other sheet types. If multiple charts are inserted or pasted, the
event will occur for each chart in the order they are inserted or pasted.

If a chart object or chart sheet is moved from one location to another, the event will not
occur. However, if the chart is moved between a chart object and a chart sheet, the event
will occur because a new chart must be created.

The WorkbookNewChart event will not occur in the following scenarios: copying or pasting a
chart sheet, changing a chart type, changing a chart data source, undoing or redoing
inserting or pasting a chart, and loading a workbook that contains a chart.

Example

The following code example displays a message box when a new chart is added to a
workbook.

VBCopy

Private Sub App_NewChart(ByVal Wb As Workbook, _

ByVal Ch As Chart)

MsgBox ("A new chart was added to: " & Wb.Name & " of type: " & Ch.Type)

End Sub

Support and feedback


Have questions or feedback about Office VBA or this documentation? Please see Office VBA
support and feedback for guidance about the ways you can receive support and provide
feedback.

Application.WorkbookNewSheet
event (Excel)
 09/13/2021

Occurs when a new sheet is created in any open workbook.

Syntax
expression.WorkbookNewSheet (Wb, Sh)

expression A variable that represents an Application object.

Parameters
Expand table
Name Required/Optional Data type Description
Wb Required Workbook The workbook.
Sh Required Object The new sheet.

Return value
Nothing

Example
This example moves the new sheet to the end of the workbook.

VBCopy
Private Sub App_WorkbookNewSheet(ByVal Wb As Workbook, _
ByVal Sh As Object)
Sh.Move After:=Wb.Sheets(Wb.Sheets.Count)
End Sub

Support and feedback

Have questions or feedback about Office VBA or this documentation?


Please see Office VBA support and feedback for guidance about the ways
you can receive support and provide feedback.
Application.WorkbookOpen event (Excel)

 09/13/2021

Occurs when a workbook is opened.

Syntax

expression.WorkbookOpen (Wb)

expression A variable that represents an Application object.

Parameters

Expand table

Name Required/Optional Data type Description

Wb Required Workbook The workbook.

Return value

Nothing

Example

This example arranges all open windows when a workbook is opened.

VBCopy

Private Sub App_WorkbookOpen(ByVal Wb As Workbook)

Application.Windows.Arrange xlArrangeStyleTiled

End Sub

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA
support and feedback for guidance about the ways you can receive support and provide
feedback.

Application.WorkbookPivotTableCloseConnection event (Excel)

 09/13/2021

Occurs after a PivotTable report connection has been closed.

Syntax

expression.WorkbookPivotTableCloseConnection (Wb, Target)

expression A variable that represents an Application object.

Parameters
Expand table

Name Required/Optional Data type Description

Wb Required Workbook The selected workbook.

Target Required PivotTable The selected PivotTable report.

Return value

Nothing

Example

This example displays a message stating that the PivotTable report's connection to its source
has been closed. This example assumes that you have declared an object of
type Workbook with events in a class module.

VBCopy

Private Sub ConnectionApp_WorkbookPivotTableCloseConnection(ByVal wbOne As


Workbook, Target As PivotTable)

MsgBox "The PivotTable connection has been closed."

End Sub

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA
support and feedback for guidance about the ways you can receive support and provide
feedback.

Application.WorkbookPivotTableOpenConnection event (Excel)

 09/13/2021

Occurs after a PivotTable report connection has been opened.

Syntax

expression.WorkbookPivotTableOpenConnection (Wb, Target)

expression A variable that represents an Application object.

Parameters

Expand table
Name Required/Optional Data type Description

Wb Required Workbook The selected workbook.

Target Required PivotTable The selected PivotTable report.

Return value

Nothing

Example

This example displays a message stating that the PivotTable report's connection to its source
has been opened. This example assumes that you have declared an object of
type Workbook with events in a class module.

VBCopy

Private Sub ConnectionApp_WorkbookPivotTableOpenConnection(ByVal wbOne As


Workbook, Target As PivotTable)

MsgBox "The PivotTable connection has been opened."

End Sub

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA
support and feedback for guidance about the ways you can receive support and provide
feedback.

Application.WorkbookRowsetComplete event (Excel)

 09/13/2021

The WorkbookRowsetComplete event occurs when the user either drills through the
recordset or invokes the rowset action on an OLAP PivotTable.

Syntax

expression.WorkbookRowsetComplete (Wb, Description, Sheet, Success)

expression A variable that represents an Application object.

Parameters

Expand table
Name Required/ Data type Description
Optional

Wb Required Workbook The workbook for which the event occurs.

Descriptio Required String A brief description of the event.


n

Sheet Required String The worksheet on which the recordset is created.

Success Required Boolean Contains a Boolean value to indicate success or


failure.

Remarks

Because the recordset is created asynchronously, the event allows automation to determine
when the action has been completed. Additionally, because the recordset is created on a
separate sheet, the event needs to be on the workbook level.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA
support and feedback for guidance about the ways you can receive support and provide
feedback.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy