VBA Cheat Sheet v1.2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Cover page

Version 1.2

VBA Cheat Sheet – Workbooks


About workbooks Closing workbooks
• Defaults to active workbook if not explicitly stated Close without saving changes
• Workbook must be open to use it wb.Close False

Reference workbooks Close and save changes


Create a workbook variable wb.Close True
Dim wb As Workbook
Loop through workbooks
Assign a workbook to workbook variable Dim wb As Workbook
'Reference a workbook by name For Each wb In Workbooks
Set wb = Workbooks("WorkbookName.xlsx") 'Action to perform on each workbook
Debug.Print wb.Name
'Reference the workbook containing the macro Next wb
Set wb = ThisWorkbook

'Reference the active workbook


Set wb = ActiveWorkbook

'Reference a workbook by order opened


Set wb = Workbooks(1)

'Reference the last workbook opened


Set wb = Workbooks(Workbooks.Count)

Create new workbooks


Create new workbook
Workbooks.Add

Create new workbook and assign to variable


Set wb = Workbooks.Add

Opening workbooks
Open a workbook
Workbooks.Open ("C:\FilePath\Name.xlsx")

Open a workbook and assign to variable


Set wb = Workbooks.Open("C:\FilePath\Name.xlsx")

Save workbooks
Save a workbook
wb.Save

Save a workbook with a new name


wb.SaveAs "C:\FilePath\NewWorkbookName.xlsx"

Save a copy of the workbook


wb.SaveCopyAs "C:\FilePath\NewWorkbookName.xlsx"

Protect and unprotect workbooks


Protect workbook without password
wb.Protect

Unprotect workbook without password


wb.Unprotect

Protect workbook with password


wb.Protect "Password"

Unprotect workbook with password


wb.Unprotect "Password"

Active a workbook
wb.Activate

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – Worksheets


About worksheets Rename worksheet
• Defaults to active workbook if not explicitly stated ws.Name = "SheetName"
• Defaults to active worksheet if not explicitly stated
Reference workbooks Activate worksheet
Worksheets("SheetName").Activate
Create a worksheet variable
Dim ws As Worksheet
Worksheet protection
Assign a worksheet to a worksheet variable Protect and unprotect worksheets
'Reference a worksheet by name 'Protect a worksheet
Set ws = Worksheets("SheetName") Worksheets("SheetName").Protect

'Reference the active worksheet 'Protect a worksheet with a password


Set ws = ActiveSheet Worksheets("SheetName").Protect "password"

'Reference a worksheet by position 'Unprotect a worksheet without a password


Set ws = Worksheets(1) Worksheets("SheetName").Unprotect

'Reference the last worksheet 'Unprotect a worksheet without a password


Set ws = Worksheets(Worksheets.Count) Worksheets("SheetName").Unprotect "password"

Add worksheets Copy worksheets


Add a worksheet 'Copy worksheets
'Add a worksheet ws.Copy
Worksheets.Add
'Move a worksheet in front of another worksheet
'Add a worksheet and assign to variable ws.Copy Before:=Worksheets("AnotherSheetName")
Set ws = Worksheets.Add
'Move a worksheet after another worksheet
ws.Copy After:=Worksheets("AnotherSheetName")
Worksheet add parameters
'Add a worksheet 'Copy multiple worksheets
Worksheets.Add Worksheets(Array("SheetName", "SheetName2", _
"SheetName3")).Copy
'Add 4 worksheets
Worksheets.Add Count:=4
Loop through workbooks
'Add a worksheet before a worksheet Loop through each worksheet
Worksheets.Add Before:=Worksheets(1) Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
'Add a worksheet after a worksheet 'Action to perform on each worksheet
Worksheets.Add After:=Worksheets(1) Debug.Print ws.Name
Next ws
'Add a worksheet to the end
Worksheets.Add After:=Worksheets(Worksheets.Count) Loop through selected worksheets
Dim ws As Worksheet
Delete worksheets For Each ws In ActiveWindow.SelectedSheets
'Action to perform on each worksheet
Delete a worksheet
Debug.Print ws.Name
ws.Delete
Next ws
Delete a worksheet without displaying a warning message
Application.DisplayAlerts = False
Apply single sheet actions to selected worksheets
Dim ws As Worksheet
ws.Delete
Dim sheetArray As Variant
Application.DisplayAlerts = True
Set sheetArray = ActiveWindow.SelectedSheets
For Each ws In sheetArray
Worksheet visibility ws.Select
There are 3 states of visibility 'Action to perform on each worksheet
'Visible Next ws
Worksheets("SheetName").Visible = xlSheetVisible sheetArray.Select

'Hidden
Worksheets("SheetName").Visible = xlSheetHidden

'Invisible
Worksheets("SheetName").Visible = xlSheetVeryHidden

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – Ranges


Declare a range Common methods & properties
All ranges on this page use a Range variable called rng Changing values
Dim rng As Range 'Change value of a range
rng.Value = "Text here“
Setting a range
'Set range on ActiveSheet (single cell) - Method 1 'Set variable to cell value
Set rng = Range("A1") Dim myVar As String
myVar = rng.Value
'Set range on ActiveSheet (single cell) - Method 2
Set rng = ActiveSheet.Range("A1") Hiding / unhiding rows and columns
'Hide Rows / Columns
'Set range based on another sheet rng.EntireColumn.Hidden = True
Dim ws As Worksheet rng.EntireRow.Hidden = True
Dim rng As Range
Set ws = Sheet("SheetName") 'Unhide Rows / Columns
Set rng = ws.Range("A1") rng.EntireColumn.Hidden = False
rng.EntireRow.Hidden = False
'Set a range (Multiple Cells)
Set rng = Range("A1:D4") Counting cells, rows and columns
'Count Rows / Columns / Cells
'Set a named range Dim count As Long
Set rng = Range("NamedRange") count = rng.Rows.count
count = rng.Columns.count
'Set rng to used range count = rng.Cells.count
Set rng = ws.UsedRange

'Set cell inside a range (Result B11) Insert cells, rows and columns
Set rng = Range("A10:D14").Cells(2, 2) 'Insert rows or columns
rng.Insert
'Set cell inside active worksheet (Result B2)
Set rng = Cells(2, 2) 'Insert cells
rng.Insert Shift:=xlDown
'Set entire column rng.Insert Shift:=xlRight
Set rng = Range("C1:D2").EntireColumn
Set rng = Range("C:D") Delete cells, rows and column
Set rng = Columns("C:D“) 'Delete rows or columns
rng.Delete
'Set entire row
Set rng = Range("C1:D2").EntireRow 'Delete cells
Set rng = Range("3:4") rng.Delete Shift:=xlUp
Set rng = Rows("3:4") rng.Insert Shift:=xlLeft

Select & activate ranges Copy and paste ranges


Loop through all files a folder 'Copy and paste everything
'Select a Range rng.Copy
rng.Select rng2.Paste

'Active a range 'Cut and paste everything


rng.Activate rng.Cut
rng2.Paste
Named ranges 'Copy and paste values only
'Create workbook named range
rng.Copy
Dim wb As Workbook
rng2.PasteSpecial Paste:=xlPasteValues
Set wb = Workbooks("WorkbookName.xlsx")
wb.Names.Add Name:="WbRange1", _
'Copy and paste formats only
RefersTo:="=Sheet1!$a$1:$D$4"
rng.Copy
rng.PasteSpecial Paste:=xlPasteFormats
'Create worksheet named range
Dim wb As Workbook
'Copy and paste with clipboard
Dim ws As Worksheet
rng.Copy Destination:=rng2
Set wb = Workbooks("WorkbookName.xlsx")
Set ws = wb.Sheets("Sheet1")
'Copy values only
ws.Names.Add Name:="WsRange1", _
rng.Value = rng2.Value
RefersTo:="=Sheet1!$a$1:$D$4"
Version 1.2

VBA Cheat Sheet - Logic


If statements Logic operators
• If and Then are needed. And Both conditions must be true.
• EndIf is needed when not a single line of code. If a < 100 And b > 100 Then
• VBA stops at the first true condition found. Or Either condition can be true.
• Ifs can be nested inside each other If a < 100 Or b > 100 Then
• There can be any number of ElseIf statements Xor Only one condition can be true.
If a < 100 Xor b > 100 Then
If (single line): Not Reverses the true or false result.
If [condition is true] Then [do thing if true] IF Not a < 100 Then

If (multiple lines): Select case


If [condition is true] Then • There can be any number of Case statements
[do thing if true]
• Case Else is optional, and is used to catch any item not
EndIf
meeting any other condition.
If with multiple conditions:
Select Case [variable]
If [condition1 is true] And [condition1 is true] Then
[do thing if true]
Case [Condition1]
EndIf [do thing if Condition1 is true]
Case [Condition2]
[do thing if Condition2 is true]
If Else: Case [ConditionX]
If [condition is true] Then
[do thing if ConditionX is true]
[do thing if true]
Case Else
Else
[do thing if no other conditions met]
[do something else]
End Select
EndIf

If ElseIf Else: Comparison operators use Case Is instead of Case.


If [condition1 is true] Then
Case Is >= 100
[do thing if condition1 is true]
ElseIf [condition2 is true]
Don’t need to use Case Is with =
[do thing if condition2 is true]
Else Use Case with number ranges
[do something else] Case 50 To 100
EndIf
Case with multiple conditions:
Nested If: Case [Condition1], [Condition2], [ConditionX]
If [condition1 is true] Then
If [condition2 is true] Then
[do thing if condition1 & 2 are true]
Case sensitive vs non-case sensitive
Else Case sensitive - at the top of the module use:
[do thing if condition1 is true & Option Compare Binary
condition2 is false]
EndIf Non-case sensitive - at the top of the module use:
Else Option Compare Text
[do thing if condition1 is false]
EndIf

Comparison operators
= Equal to
<> Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet - Loops


For Loop Do While
• Cycles through a sequence of numbers • Loops while the condition remains true
• Use Step to increment by a number other than 1 • 2 forms: (1) check condition at the start (2) check condition at
• Use Exit For to leave a loop early end
• If using For Loop to delete objects always use Step -1 • Exit loop by using Exit Do

For Loop For Loop with Step Check condition at start


Dim i as Integer Dim i as Integer If condition is false at the start, code in loop never executes.
For i = 1 To 100 For i = 1 To 100 Step 5 Structure: Example:
Range("A" & i) = i Range("A" & i) = i Do While [condition1] Dim i As Integer
Next i Next i [Thing to do] i = 1
Loop Do While i < 10
MsgBox i
For Loop in reverse (Step -1) For Loop with Exit For i = i + 1
Dim i as Integer Dim i as Integer Loop
For i = 100 To 1 Step -1 For i = 1 To 100
Range("A" & i) = i Range("A" & i) = I Check condition at end
Next i If i > 20 Then Exit For Code in the loop is executed at lease once
Next i
Structure: Example:
Do Dim i As Integer
[Thing to do] i = 1
Nested For Loop Loop While [condition1] Do
Dim i as Integer MsgBox i
Dim j as Integer i = i + 1
Loop While i < 10
For i = 1 To 10
For j = 1 To 5 Do Until
Cells(i, j) = i + j • Loops until a condition is true
Next j • 2 forms: (1) check condition at the start (2) check condition at
Next i
end
For Each Loop • Exit loop by using Exit Do
• Cycles each object in a collection
• Use Exit For to leave a loop early Check condition at start
If condition is true at the start, code in loop never executes.
For Each Loop (Structure) Structure: Example:
Dim [Variable] as [Object] Do Until [condition1] Dim i As Integer
For Each [Variable] In [Object Collection] [Thing to do] i = 1
[Thing to do for each object] Loop Do Until i > 5
Next [Variable] MsgBox i
i = i + 1
Loop
For Each Loop through cells in Range
Dim c as Range
For Each c In ActiveSheet.Range("A1:B4") Check condition at end
c.value = c.Address Code in the loop is executed at least once
Next c Structure: Example:
Do Dim i As Integer
For Each Loop through worksheets in workbook [Thing to do] i = 1
Dim ws As Worksheet Loop Until [condition1] Do
For Each ws In ActiveWorkbook.Sheets MsgBox i
MsgBox ws.Name i = i + 1
Next ws Loop Until i > 5

While
For Each Loop with Exit For
• Works the same as Do Until
Dim c As Range
For Each c In ActiveSheet.Range("A1:B4") • Condition is checked at the start
c.Value = c.Row Structure: Example:
If c.Value >= 3 Then MsgBox "Exit here“ While [condition1] Dim i As Integer
Exit For [Thing to do] i = 10
Next c Wend While i < 10
MsgBox i
i = i + 1
Wend

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – Tables (page 1)


About Tables Changing Tables
• Tables are known as ListObjects in VBA Change name of Table
tbl.Name = "myNewTable"
Reference Tables
Create a Table variable Resizing a Table
Dim ws As Worksheet tbl.Resize Range("$A$1:$D$10")
Dim tbl As ListObject
Remove auto filter
Set ws = Sheets("Sheet1") tbl.ShowAutoFilterDropDown = False
Set tbl = ws.ListObjects("myTable")
Set Table style
Reference parts of a Table tbl.TableStyle = "TableStyleLight15"
'Entire Table range
tbl.Range.Select Remove row stripes
tbl.ShowTableStyleRowStripes = False
'Table data range only
tbl.DataBodyRange.Select Hide header row
tbl.ShowHeaders = False
'Single cell within a Table (row 2, column4)
tbl.DataBodyRange(2, 4).Select
Columns & rows
'Table column including header by position Add columns & rows
tbl.ListColumns(2).Range.Select 'Add column at the end
tbl.ListColumns.Add
'Table column including header by name
tbl.ListColumn("ColumnName").Range.Select 'Add column in position 2
tbl.ListColumns.Add Position:=2
'Table column, data only, by position
tbl.ListColumns(2).DataBodyRange.Select 'Add row at bottom
tbl.ListRows.Add
'Table column, data only, by name
tbl.ListColumns("ColumnName").DataBodyRange.Select 'Add row at position 2
tbl.ListRows.Add Position:=2
'Entire header row
tbl.HeaderRowRange.Select Delete columns & rows
'Delete column 2
'Single cell within header row tbl.ListColumns(2).Delete
tbl.HeaderRowRange(2).Select
'Delete a column by name
'Entire total row tbl.ListColumns("ColumnName").Delete
tbl.TotalsRowRange.Select

'Single cell within total row 'Delete row 2


tbl.TotalsRowRange(2).Select tbl.ListRows(2).Delete

'Single row of data 'Delete multiple rows


tbl.ListRows(2).Range.Select tbl.Range.Rows("2:3").Delete

'Reference parts of table using range object Count columns & rows
ws.Range("myTable[ColumnName]").Select 'Count columns
tbl.ListColumns.Count
Converting to/from a Table
Convert current region to Table 'Count rows
Dim tableName As String tbl.ListRows.Count
Dim tableRange As String
tableName = "myTable"
tableRange = “A1:D10"
ws.ListObjects.Add(SourceType:=xlSrcRange, _
Source:=Range(tableRange), _
xlListObjectHasHeaders:=xlYes _
).Name = tableName

Convert Table back to range


tbl.Unlist

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – Tables (page 2)


Loop through Tables Miscellaneous
Loop through all tables on a worksheet Enter data into table from array
Dim ws As Worksheet Dim myArray As Variant
Dim tbl As ListObject myArray = Range("A2:D2")
Set ws = ActiveSheet tbl.ListRows(2).Range.Value = myArray
For Each tbl In ws.ListObjects
'Action to perform for each table Simulate ActiveTable object
Debug.Print tbl.Name If active cell is not in a Table, then ActiveTable Is Nothing = True
Next tbl Dim ActiveTable As ListObject
On Error Resume Next
Loop through all tables in a workbook Set ActiveTable = ActiveCell.ListObject
Dim wb As Workbook On Error GoTo 0
Dim ws As Worksheet
Dim tbl As ListObject If ActiveTable Is Nothing Then
Set wb = ActiveWorkbook 'ActiveCell not in Table
For Each ws In wb.Worksheets Else
For Each tbl In ws.ListObjects 'ActiveCell is in Table
'Action to perform for each table End If
Debug.Print tbl.Name
Next tbl
Next ws Show Table data entry form
Only works if Table starts at A1
Table total row Dim ws As Worksheet
Display total row with value in last column Set ws = ActiveSheet
tbl.ShowTotals = True ws.ShowDataForm

Add calculation to other columns


'Change calculation by column position
tbl.ListColumns(2).TotalsCalculation = _
xlTotalsCalculationAverage

'Change calculation by column name


tbl.ListColumns("ColumnName").TotalsCalculation = _
xlTotalsCalculationAverage

Other calculation types


xlTotalsCalculationNone
xlTotalsCalculationAverage
xlTotalsCalculationCount
xlTotalsCalculationCountNums
xlTotalsCalculationMax
xlTotalsCalculationMin
xlTotalsCalculationSum
xlTotalsCalculationStdDev
xlTotalsCalculationVar

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – Names


About Names Name Visibility
• Names can refer to ranges, formulas and constants Names can be hidden from the Name Manager.
• Can have workbook or worksheet scope Names("myNamedRange").Visible = False
• Print_Area is the name used for the print range
Loop Through Names
Reference names For Each through all Names
Create Name variable Dim nm As Name
Dim wb As Workbook For Each nm In wb.Names
Dim nm As Name 'Action to perform for each table
Set wb = ActiveWorkbook MsgBox nm.Name
Set nm = wb.Names("myNamedConstant") Next

Reference parts of a Name


'Name of a Name
MsgBox nm.Name

'RefersTo part of a Name


MsgBox nm.RefersTo

Add Names
Create Name with workbook scope
wb.Names.Add Name:="myNamedRange", _
RefersTo:="=Sheet1!$C$1:$D$5"

Create Name with worksheet scope


ws.Names.Add Name:="myNamedRange", _
RefersTo:="=Sheet1!$C$1:$D$5"

Create Name with a formula


Formulas must be created using the R1C1 reference method
wb.Names.Add Name:="myNamedFormula", _
RefersTo:="=SUM(Sheet1!R2C2:R4C4)"

Create Name with a constant


wb.Names.Add Name:="myNamedConstant", _
RefersTo:="=20%"

Delete a Name
Delete Name
If name macthes will delete workbook and worksheet Names
wb.Names("myNamedRange").Delete

Delete worksheet scoped Name


Only deletes the worksheet scoped Name
wb.Names("Sheet1!myNamedRange").Delete

Change a Name
Change name and Refers to of a Name
nm.Name = "changedMyNamedConstant“
nm.RefersTo = "=50%"

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – Filters


About Filters Applying Sort
• For many AutoFilter actions need to check if AutoFilterMode Applying column sorting
applied already, else causes an error ws.AutoFilter.Sort.SortFields.Add _
Order:=xlAscending, _
Applying AutoFilter SortOn:=xlSortOnValues, _
Key:=Range("A1:A7")
Check if AutoFilter already exists
ws.AutoFilter.Sort.Apply
If ws.AutoFilterMode = True Then
'Do something
End If Clear sorting
ws.AutoFilter.Sort.SortFields.Clear
Apply AutoFilter to current region
ws.Range("A1").AutoFilter

Remove AutoFilter
ws.AutoFilterMode = False

Hide a filter on a field


ws.Range("A1").AutoFilter Field:=1,_
Visibledropdown:=False

Get Range of the AutoFilter


MsgBox ws.AutoFilter.Range.Address

Filtering
Filter with value criteria
ws.Range("A1").AutoFilter _
Field:=1, Criteria1:="=Apple", _
Operator:=xlOr, Criteria2:="=Banana"

Search operators:
Equals: Criteria1:="=Apple"
Does Not Equal: Criteria1:="<>Apple"
Begins with: Criteria1:="=Apple*"
Ends with: Criteria1:="=*Apple"
Contains: Criteria1:="=*Apple*"
Does Not Contain: Criteria1:="<>*Apple*"

Search logic:
Or: Operator:=xlOr
And: Operator:=xlAnd

Show all data


ws.ShowAllData

Filter by color (RGB)


ws.Range("$A$1").AutoFilter _
Field:=1, Criteria1:=RGB(255, 255, 0), _
Operator:=xlFilterCellColor

Filter on no color
ws.Range("$A$1").AutoFilter Field:=1,_
Operator:=xlFilterNoFill

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – PivotTables


Reference a PivotTable Add and remove fields
Reference a PivotTable Add fields to the rows, columns and filters
Dim ws As Worksheet pvt.PivotFields("fieldName").Orientation = xlRowField
Dim pvt As PivotTable pvt.PivotFields("fieldName").Orientation = xlColumnField
pvt.PivotFields("fieldName").Orientation = xlPageField

Set ws = ActiveWorkbook.Sheets("Sheet1")
Set pvt = ws.PivotTables("myPivotTable") Change position of field
pvt.PivotFields("fieldName").Position = 1
Create a PivotTable
Create a PivotTable Add field to values section
Dim wb As Workbook pvt.AddDataField pvt.PivotFields("fieldName"), _
Dim ws As Worksheet "calcName", xlSum
Dim pvtCache As PivotCache
Dim pvt As PivotTable 11 Calculation options:
xlAverage xlMin xlSum
Set wb = ActiveWorkbook xlCount xlProduct xlVar
Set ws = wb.Sheets("Sheet1") xlCountNums xlStDev xlVarP
xlMax xlStDevP
Set pvtCache = wb.PivotCaches.Create _
(SourceType:=xlDatabase, _ Remove field from PivotTable
SourceData:="Sheet1!R2C2:R10C4") pvt.PivotFields("fieldName").Orientation = xlHidden

Set pvt = pvtCache.CreatePivotTable _ Clear all fields


(TableDestination:="Sheet1!R2C6", _ pvt.ClearTable
tableName:="myPivotTable")

PivotTable Filters
Delete a PivotTable Clear existing filters
pvt.PivotFields("fieldName").ClearAllFilters
Delete a PivotTable
pvt.TableRange2.Clear
Add field filter
pvt.PivotFields("fieldName").PivotFilters. _
Change PivotTable source Add2 Type:=xlCaptionEquals, _
Create a PivotTable Value1:="Apple"
Dim wb As Workbook
Dim ws As Worksheet
Dim pvtCache As PivotCache Add calculated field
Dim pvt As PivotTable Add calculated field
pvt.CalculatedFields.Add _
Set wb = ActiveWorkbook "calcFieldName", "=fieldName2+FieldName3"
Set ws = wb.Sheets("Sheet1")
Set pvt = ws.PivotTables("myPivotTable")

Set pvtCache = wb.PivotCaches.Create _


(SourceType:=xlDatabase, _
SourceData:="Sheet1!R2C2:R12C4")
pvt.ChangePivotCache pvtCache

Turn off AutoFit columns


Delete a PivotTable
pvt.HasAutoFormat = False

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – Charts (page 1)


About Charts Basic chart settings (continued)
• Charts can be Chart Objects (face of the worksheet) or Chart 'Change the setting to show only visible cells
Sheets (separate sheets). This page is for Chart Objects. cht.PlotVisibleOnly = True
• Chart Objects are a collection of objects
'Change the gap space between bars
• Each Chart Object contains a Chart
cht.ChartGroups(1).GapWidth = 50
Reference charts 'Change the overlap setting of bars
Reference a chart object cht.ChartGroups(1).Overlap = 75
Dim ws As Worksheet
Dim cht As Chart
Set ws = ActiveWorkbook.Sheets("Sheet1")
Set cht = ws.ChartObjects("Chart 1").Chart Chart axis
There are four chart axis:
Reference the active chart • xlValue • xlCategory
Dim cht As Chart • xlValue, xlSecondary • xlCategory, xlSecondary
Set cht = ActiveChart These are used interchangeably in the examples.
'Set chart axis min and max
Loop through chart objects cht.Axes(xlValue).MaximumScale = 25
Dim ws As Worksheet cht.Axes(xlValue).MinimumScale = 10
Dim chtObj As ChartObject cht.Axes(xlValue).MaximumScaleIsAuto = True
Set ws = Worksheets("Sheet1") cht.Axes(xlValue).MinimumScaleIsAuto = True
For Each chtObj In ws.ChartObjects
'Code to be applied to each ChartObjects 'Display axis
'refer to the Chart using chtObj.Chart cht.HasAxis(xlCategory) = True
Next chtObj
'Hide axis
cht.HasAxis(xlValue, xlSecondary) = False
Basic chart settings
'Change chart type (examples only, others exist). 'Display axis title
cht.ChartType = xlArea cht.Axes(xlCategory, xlSecondary).HasTitle = True
cht.ChartType = xlLine
cht.ChartType = xlPie 'Hide axis title
cht.ChartType = xlColumnClustered cht.Axes(xlValue).HasTitle = False
cht.ChartType = xlColumnStacked
cht.ChartType = xlColumnStacked100 'Change axis title text
cht.ChartType = xlArea cht.Axes(xlCategory).AxisTitle.Text = "My Title"
cht.ChartType = xlAreaStacked
cht.ChartType = xlBarClustered 'Reverse the order of a category axis
cht.ChartType = xlBarStacked cht.Axes(xlCategory).ReversePlotOrder = True
cht.ChartType = xlBarStacked100

'Create an empty chart embedded on a worksheet Gridlines


Set cht = ws.Shapes.AddChart2.Chart 'Add gridlines
cht.SetElement (msoElementPrimaryValueGridLinesMajor)
cht.SetElement (msoElementPrimaryCategoryGridLinesMajor)
'Select source for a chart cht.SetElement (msoElementPrimaryValueGridLinesMinorMajor)
Dim rng As Range cht.SetElement (msoElementPrimaryCategoryGridLinesMinorMajor)
Set rng = ws.Range("A1:B4")
cht.SetSourceData Source:=rng 'Delete gridlines
cht.Axes(xlValue).MajorGridlines.Delete
'Delete a ChartObject cht.Axes(xlValue).MinorGridlines.Delete
cht.Parent.Delete 'Method 1 cht.Axes(xlCategory).MajorGridlines.Delete
chtObk.Delete 'Method 2 cht.Axes(xlCategory).MinorGridlines.Delete

'Set the size/position of a ChartObject - method 1 'Change colour of gridlines


cht.Parent.Height = 200 cht.Axes(xlValue).MajorGridlines.Format.Line. _
cht.Parent.Width = 300 ForeColor.RGB = RGB(255, 0, 0)
cht.Parent.Left = 20
cht.Parent.Top = 20 'Change transparency of gridlines
cht.Axes(xlValue).MajorGridlines.Format.Line. _
'Set the size/position of a ChartObject - method 2 Transparency = 0.5
chtObj.Height = 200
chtObj.Width = 300
chtObj.Left = 20
chtObj.Top = 20

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – Charts (page 2)


Chart title Chart series (continued)
'Display chart title Loop through each chart series
cht.HasTitle = True For Each srs In cht.SeriesCollection
'Do something to each series
'Hide chart title 'Refer to each with srs.
cht.HasTitle = False Next srs
Change series data
'Change chart title text 'Change series source data and name
cht.ChartTitle.Text = "My Chart Title" srs.Values = "=Sheet1!$C$2:$C$6"
srs.Name = "=""Change Series Name"""
'Position the chart title
cht.ChartTitle.Left = 10 'Add a new chart series
cht.ChartTitle.Top = 10 Set srs = cht.SeriesCollection.NewSeries
srs.Values = "=Sheet1!$C$2:$C$6"
'Format the chart title srs.Name = "=""New Series""“
cht.ChartTitle.TextFrame2.TextRange.Font.Name = "Calibri"
cht.ChartTitle.TextFrame2.TextRange.Font.Size = 16
cht.ChartTitle.TextFrame2.TextRange.Font.Bold = msoTrue 'Set values for the X axis when using XY Scatter
cht.ChartTitle.TextFrame2.TextRange.Font.Bold = msoFalse srs.XValues = "=Sheet1!$D$2:$D$6"
cht.ChartTitle.TextFrame2.TextRange.Font.Italic = msoTrue Display data labels
cht.ChartTitle.TextFrame2.TextRange.Font.Italic = msoFalse 'Display data labels on all points in the series
srs.HasDataLabels = True
Chart legend
'Display the legend 'Hide data labels on all points in the series
cht.HasLegend = True srs.HasDataLabels = False

'Hide the legend 'Position data labels


cht.HasLegend = False 'Must be a valid option for the chart type.
srs.DataLabels.Position = xlLabelPositionAbove
'Position the legend srs.DataLabels.Position = xlLabelPositionBelow
cht.Legend.Position = xlLegendPositionTop srs.DataLabels.Position = xlLabelPositionLeft
cht.Legend.Position = xlLegendPositionRight srs.DataLabels.Position = xlLabelPositionRight
cht.Legend.Position = xlLegendPositionLeft srs.DataLabels.Position = xlLabelPositionCenter
cht.Legend.Position = xlLegendPositionCorner srs.DataLabels.Position = xlLabelPositionInsideEnd
cht.Legend.Position = xlLegendPositionBottom srs.DataLabels.Position = xlLabelPositionInsideBase
srs.DataLabels.Position = xlLabelPositionOutsideEnd
'Allow legend to overlap the chart Series formatting
'False = allow overlap, True = due not overlap 'Change fill colour
cht.Legend.IncludeInLayout = False srs.Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
cht.Legend.IncludeInLayout = True
'Change line colour
'Move legend to a specific point srs.Format.Line.ForeColor.RGB = RGB(255, 0, 0)
cht.Legend.Left = 20
cht.Legend.Top = 200 'Change visibility of line
cht.Legend.Width = 100 srs.Format.Line.Visible = msoTrue
cht.Legend.Height = 25
'Change line weight
Plot area srs.Format.Line.Weight = 10
'Set the size and position of the PlotArea
cht.PlotArea.Left = 20 'Change line style
cht.PlotArea.Top = 20 srs.Format.Line.DashStyle = msoLineDash
cht.PlotArea.Width = 200 srs.Format.Line.DashStyle = msoLineSolid
cht.PlotArea.Height = 150 srs.Format.Line.DashStyle = msoLineSysDot
srs.Format.Line.DashStyle = msoLineSysDash
srs.Format.Line.DashStyle = msoLineDashDot
Chart series srs.Format.Line.DashStyle = msoLineLongDash
Reference chart series srs.Format.Line.DashStyle = msoLineLongDashDot
'Method 1 srs.Format.Line.DashStyle = msoLineLongDashDotDot
Dim srs As Series
Set srs = cht.SeriesCollection(1)

'Method 2
Dim srs As Series
Set srs = cht.SeriesCollection("Series Name")

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – Charts (page 3)


Chart series (continued)
'Change marker type
srs.MarkerStyle = xlMarkerStyleAutomatic
srs.MarkerStyle = xlMarkerStyleCircle
srs.MarkerStyle = xlMarkerStyleDash
srs.MarkerStyle = xlMarkerStyleDiamond
srs.MarkerStyle = xlMarkerStyleDot
srs.MarkerStyle = xlMarkerStyleNone

'Change marker border color


srs.MarkerForegroundColor = RGB(255, 0, 0)

'Change marker fill color


srs.MarkerBackgroundColor = RGB(255, 0, 0)

'Change marker size


srs.MarkerSize = 8

Error bars
'Turn error bars on/off
srs.HasErrorBars = True
srs.HasErrorBars = False

'Change end style of error bar


srs.ErrorBars.EndStyle = xlNoCap
srs.ErrorBars.EndStyle = xlCap

'Change color of error bars


srs.ErrorBars.Format.Line.ForeColor.RGB = RGB(255, 0, 0)

'Change thickness of error bars


srs.ErrorBars.Format.Line.Weight = 5

'Error bar settings


srs.ErrorBar Direction:=xlY, _
Include:=xlPlusValues, _
Type:=xlFixedValue, _
Amount:=100

'Alternatives options for the error bar settings are


Direction:=xlX
Include:=xlMinusValues
Include:=xlPlusValues
Include:=xlBoth
Type:=xlFixedValue
Type:=xlPercent
Type:=xlStDev
Type:=xlStError
Type:=xlCustom

Points
Reference points
Dim srs As Series
Dim pnt As Point

Set srs = cht.SeriesCollection(1)


Set pnt = srs.Points(1)
Loop through points
Dim srs As Series
Dim pnt As Point
Set srs = cht.SeriesCollection(1)
For Each pnt In srs.Points
'Do something to each point, using "pnt."
Next pnt
Point data labels
'Turn on data label
pnt.HasDataLabel = True

'Set the position of a data label


pnt.DataLabel.Position = xlLabelPositionCenter

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – Images


Reference image Image properties (continued)
Create image variable 'Change image placement options
Dim ws As Worksheet img.Placement = xlFreeFloating
Dim img As Shape img.Placement = xlMoveAndSize
Set ws = ActiveWorkbook.Sheets("Sheet1") img.Placement = xlMove
Set img = ws.Shapes("myImage")
'Lock image (prevent editing when sheet protected)
Insert image img.Locked = True 'Opposite value = False
Insert image and assign to variable
'Rotate to specific position
Dim img As Shape
img.Rotation = 90
Dim imagePath As String
Dim rng As Range
imagePath = "C:\Users\Documents\myImage.png" Get image size and position properties
Set rng = ActiveCell MsgBox img.Top
Set img = ws.Shapes.AddPicture( _ MsgBox img.Left
Filename:=imagePath, _ MsgBox img.Height
LinkToFile:=msoFalse, _ MsgBox img.Width
SaveWithDocument:=msoTrue, _ MsgBox img.ZOrderPosition
Left:=rng.Left, _ MsgBox img.TopLeftCell.Address
Top:=rng.Top, _
Width:=-1, _ Place image in relation to cells
Height:=-1) Centre image over a cell
'center image in cell
Insert shape around active cells Set cellLocation = ws.Range("B4")
Dim ws As Worksheet
Dim img As Shape img.Top = cellLocation.Top + _
Dim rng As Range (cellLocation.Height / 2) - _
Set ws = ActiveSheet (img.Height / 2)
Set rng = Selection img.Left = cellLocation.Left + _
Set img = ws.Shapes.AddShape( _ (cellLocation.Width / 2) - _
msoShapeRectangle, _ (img.Width / 2)
Left:=rng.Left, _
Top:=rng.Top, _ Stretch image over cells
Width:=rng.Width, _ Set rng = ws.Range("A2:D10")
Height:=rng.Height)
img.LockAspectRatio = msoFalse
img.Fill.Visible = msoFalse
img.Line.ForeColor.RGB = RGB(255, 0, 0) img.Left = rng.Left
img.Line.Weight = 2.25 img.Top = rng.Top
img.Width = rng.Width
Image properties img.Height = rng.Height
Set common image properties
'Set if image’s aspect ratio is locked. Check if selection is in image
img.LockAspectRatio = msoTrue If TypeName(Selection) = "Picture" Then
'Object is a picture
'Change top, left, width and height of image End If
img.Top = 100
img.Left = 100 Export image from Excel
img.Width = 100 Copy picture to chart background, then export empty chart
img.Height = 100 Dim img As Shape
Dim ws As Worksheet
'Change Z-order. Can bring forward / send backward Dim tempChartObj As ChartObject
img.ZOrder msoBringToFront Dim savePath As String
img.ZOrder msoSendToBackward
Set ws = ActiveWorkbook.Sheets("Sheet1")
'Change image name Set img = ws.Shapes("Picture 1")
img.Name = "imgName" Set tempChartObj = ActiveSheet.ChartObjects.Add _
(0, 0, myPic.Width, myPic.Height)
'Flip image horizontal or vertical savePath = "C:\Users\Documents\mySavedPic.jpg“
img.Flip msoFlipHorizontal
img.Flip msoFlipVertical img.Copy
tempChartObj.Chart.ChartArea.Select
'Change image visibility tempChartObj.Chart.Paste
img.Visible = msoFalse tempChartObj.Chart.Export savePath
img.Visible = msoTrue tempChartObj.Delete

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – PDFs


Declaring a PDF file name PDF Options
All the Macros on this page use a the following file path PDF Print options
Dim pdfFile As String 'Open the document after save: True / False
pdfFile = "C:\Users\marks\Documents\PDFName.pdf" OpenAfterPublish:=False

'Include Excel document properties in PDF: True / False


IncludeDocProperties:=True
Create a PDFs from Excel
'Adhere to the existing Print Areas: True / False
Save declared worksheet IgnorePrintAreas:=False
Dim ws As Worksheet
Set ws = Worksheets("SheetName") 'Set the output quality of the created document
'xlQualityMinimum / xlQualityStandard
ws.ExportAsFixedFormat Type:=xlTypePDF, _
Quality:=xlQualityStandard
Filename:=pdfFile
'The page to start printing from.
Save active worksheet From:=1
ActiveWorksheet.ExportAsFixedFormat
'The page to print to.
Type:=xlTypePDF, _
To:=2
Filename:=pdfFile

Save multiple worksheets in single PDF Example using all options


Dim sheetArray As Variant ActiveSheet.ExportAsFixedFormat _
sheetArray = Array("Sheet1", "Sheet2") Type:=xlTypePDF, _
Sheets(sheetArray).Select pFilename:=pdfFile, _
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _ OpenAfterPublish:=False, _
Filename:=pdfFile IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
Save declared workbook Quality:=xlQualityStandard, _
Dim wb as Workbook From:=1, To:=2
Set wb = Workbooks("WorkbookName.xlsx")
wb.ExportAsFixedFormat Type:=xlTypePDF,
_ Filename:=pdfFile
Save active workbook
ActiveWorkbook.ExportAsFixedFormat
_Type:=xlTypePDF,
_ Filename:=pdfFile

Save declared range


Dim rng As Range
Set rng = Sheets("Sheet1").Range("A1:H20")
rng.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=pdfFile

Save selection
Selection.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=pdfFile

Save declared chart


Dim ws As Worksheet
Dim cht As Chart
Set ws = Worksheets("SheetName")
Set cht = ws.ChartObjects("Chart 1").Chart
cht.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=pdfFile

Save active chart


ActiveChart. ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=pdfFile
Version 1.2

VBA Cheat Sheet - Arrays (page 1)


About arrays Looping through array
• Arrays: stores data of same variable type (type cannot change) Index of first element LBound(arr)
• Size / L Index of last element UBound(arr)
• length: the number of elements in the array
• Element: one item with an array Loop through 1-dimension array
• Index: the position of the element within the array Dim i As Long
• Static arrays: the size is fixed at creation (cannot be resized) For i = LBound(arr) To UBound(arr)
• Dynamic arrays: the size can be adjusted as the macro runs [Thing to do for element]
Next i
• Array index starts counting at 0, can change to count from 1 by
using Option Base 1 at the start of the code module
Loop through 2-dimension array
• Arrays created from ranges always have 2 dimensions Dim i As Long
Declaring arrays Dim j As Long
Static (1 dimension) Dim arr(0 To 10) As Integer
For i = LBound(arr, 1) To UBound(arr, 1)
Static (1 dimension) Dim arr(10) As Integer For j = LBound(arr, 2) To UBound(arr, 2)
Static (2 dimension) Dim arr(0 To 5, 0 To 5) As Integer [Thing to do for element]
Dynamic Dim arr() As Integer Next j
Dynamic Dim arr As Variant Next i

Resizing dynamic arrays Loop through array with For Each


• Resizing with ReDim will clear the values in the array. Dim element As Variant
• Resizing with ReDim Preserve keeps in the values in the array, For Each element In arr
but only last dimension can be resized Thing to do for element]
ReDim arr(0 To 10) Next element
Resize
Resize + keep data ReDim Preserve arr(0 To 10)
Array functions
Assign values to an array Check if value is in array
Assign values individually Function IsValueInArray(arr As Variant, _
Dim arr(0 To 2) As String find As Variant) As Boolean
arr(1) = "Alpha" Dim element As Variant
arr(2) = "Bravo" For Each element In arr
arr(3) = "Charlie" If element = find Then
IsValueInArray = True
Exit Function
Assign values individually from list
End If
Dim arr As Variant
Next element
arr = Array("Alpha", "Bravo", "Charlie")
IsValueInArray = False
End Function
Assign values individually from list (multi dimension)
Dim arr As Variant
arr = Array(Array("Alpha", "Bravo"), Array(1,2)) Return index position of a matched value in an array
Function PositionInArray(arr As Variant, _
find As Variant) As Variant
Assign values by splitting string with a separator
Dim i As Long
Dim arr As Variant
For i = LBound(arr) To UBound(arr)
arr = Split("Alpha, Bravo, Charlie", ", ")
If arr(i) = find Then
PositionInArray = i
Assign values from range Exit Function
Dim arr As Variant End If
arr = ActiveSheet.Range("A1:C3").Value2 Next i
PositionInArray = False
End Function

Convert array to string or range


Convert array to string with separator
Dim arr As Variant
arr = Array("Alpha", "Bravo", "Charlie")
Msg Box Join(arr, " ;")

Convert array to range


Dim arr As Variant
arr = Array("Alpha", "Bravo", "Charlie")
ActiveSheet.Range("A1:C1") = arr

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – Arrays (page 2)


Array functions (continued)
Reverse the order of an array
Function ReverseArray(arr As Variant)
Dim temp As Variant
Dim i As Long
Dim arrSize As Long
Dim arrMid As Long
arrSize = UBound(arr)
arrMid = (UBound(arr) - LBound(arr)) \ 2 + _
LBound(arr)
For i = LBound(arr) To arrMid
temp = arr(arrSize)
arr(arrSize) = arr(i)
arr(i) = temp
arrSize = arrSize - 1
Next i
ReverseArray = arr
End Function

Sort an array
Function SortingArrayBubbleSort(arr As Variant)
Dim i As Long
Dim j As Long
Dim temp As Variant
For i = LBound(arr) To UBound(arr) - 1
For j = i + 1 To UBound(arr)
If arr(i) > arr(j) Then
temp = arr(j)
arr(j) = arr(i)
arr(i) = temp
End If
Next j
Next i
SortingArrayBubbleSort = arr
End Function

Filter an array
Function FilterArray(arr As Variant, _
filterValue As Variant)
FilterArray = Filter(arr, filterValue)
End Function

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – Files & Folders (page 1)


About files an folders Copy, move and delete files
• Folder paths always need to end with a slash ( \ ) Rename or move a file or folder
Name "C:\Users\marks\Documents\FileName.xlsx" _
File functions As "C:\Users\marks\Documents\NewFileName.xlsx"
Check if a file exists (True = exists, False = does not)
Function DoesFileExist(filePath) As Boolean Copy a file
DoesFileExist = Dir(filePath) <> "" FileCopy "C:\Users\marks\Documents\File.xlsx", _
End Function "C:\Users\marks\Documents\Copied File.xlsx"

Check if a folder exists (True = exists, False = does not) Delete a file
Function DoesFolderExist(folderPath As String) _ Kill "C:\Users\marks\Documents\DeleteMe.xlsx"
As Boolean
DoesFolderExist = Dir(folderPath, _ Delete files using wildcards (? = 1 character, * = 2+ characters)
vbDirectory) <> "" Kill "C:\Users\marks\Documents\*.xlsx"
End Function
Delete all files in a folder
Check if a file is already open Kill "C:\Users\marks\Documents\*.*"
Function IsFileOpen(fileName As String)
Dim fileNum As Integer Delete a folder
Dim errNum As Integer Kill "C:\Users\marks\Documents\Delete Folder\“ _
On Error Resume Next & "*.*"
fileNum = FreeFile() RmDir folderPath
Open fileName For Input Lock Read As #fileNum
Close fileNum
errNum = Err
Create a new folder
MkDir "C:\Users\marks\Documents\New folder"
On Error GoTo 0
Select Case errNum
Case 0 'file closed Create all folders along a file path
IsFileOpen = False Sub MakeAllFolders(folderPath As String)
Case 70 'file already open
IsFileOpen = True Dim individualFolders() As String
Case Else 'Something else went wrong Dim tempFolderPath As String
IsFileOpen = errNum Dim arrayElement As Variant
End Select
End Function individualFolders = Split(folderPath, "\")

For Each arrayElement In individualFolders


Get file system attributes tempFolderPath = tempFolderPath & _
Function CheckFileAttribute(filePath As String, _ arrayElement & "\"
fileAttribute As Long) If Dir(tempFolderPath, vbDirectory) = "" Then
CheckFileAttribute = (GetAttr(filePath) _ MkDir tempFolderPath
And fileAttribute) <> 0 End If
End Function Next arrayElement
The fileAttribute argument can be:
Attribute Enumerator Description End Sub
vbNormal 0 Normal
vbReadOnly 1 Read-only Loop files in a folder
vbHidden 2 Hidden Loop through all files a folder
vbSystem 4 System Dim folderName As Variant
vbVolume 8 Volume folderName = Dir("C:\Users\marks\Documents\")
vbDirectory 16 Directories While folderName <> ""
[Thing to do for each file]
folderName = Dir
Wend

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

VBA Cheat Sheet – Files & Folders (page 2)


Selecting files with the dialog box
Select a file with the dialog box
Function SelectFile(dialogTitle As String)
Dim dialogBox As FileDialog
Set dialogBox = _
Application.FileDialog(msoFileDialogOpen)
dialogBox.AllowMultiSelect = False
dialogBox.Title = dialogTitle
If dialogBox.Show = -1 Then
SelectFile = dialogBox.SelectedItems(1)
Else
SelectFile = ""
End If
End Function

Select a folder with the dialog box


Function selectFolder(dialogTitle As String)
Dim dialogBox As FileDialog
Set dialogBox = _
Application.FileDialog(msoFileDialogFolderPicker)
dialogBox.Title = dialogTitle
If dialogBox.Show = -1 Then
selectFolder = dialogBox.SelectedItems(1)
Else
selectFolder = ""
End If
End Function

Zipping and unzipping folders


Zip a folder
Sub CreateZipFile(folderToZipPath As Variant, _
zippedFileFullName As Variant)
Dim ShellApp As Object
Open zippedFileFullName For Output As #1
Print #1, Chr$(80) & Chr$(75) & Chr$(5) & _
Chr$(6) & String(18, 0)
Close #1
Set ShellApp = CreateObject("Shell.Application")
ShellApp.Namespace(zippedFileFullName).CopyHere _
ShellApp.Namespace(folderToZipPath).items
On Error Resume Next
Do Until ShellApp.Namespace(zippedFileFullName). _
items.Count = _
ShellApp.Namespace(folderToZipPath).items.Count
Application.Wait (Now + TimeValue("0:00:01"))On
Error GoTo 0
End Sub

Unzip a folder
Sub UnzipAFile(zippedFileFullName As Variant,_
unzipToPath As Variant)
Dim ShellApp As Object
Set ShellApp = CreateObject("Shell.Application")
ShellApp.Namespace(unzipToPath).CopyHere
ShellApp.Namespace(zippedFileFullName).items
End Sub

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

Visual Basic Editor – Shortcut Keys (Page 1)


On its own Shift Ctrl Alt Ctrl + Shift
F1 Help
F2 Object Procedure Activate Previous
browser definition object box position
F3 Find next for Find previous
last searched
word
F4 Properties Find next Close window Close VBE
window
F5 Runs selected Run error
procedure handler
F6 Toggle split
windows
F7 Displays code
window of
object
F8 Step into Step over line Run to cursor Step error Step out of
by line handler code

F9 Toggle Quick watch Clear all


breakpoint breakpoints
F10 Activate Show right- Activate
menu bar click menu menu bar
F11 Toggle
between VBE
& application

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

Visual Basic Editor – Shortcut Keys (Page 2)


On its own Shift Ctrl Alt Ctrl + Shift
Insert Toggle insert Paste Copy
mode
Delete Delete Delete to end
of word
Home Beginning of Select to start Move to top
line of line of module
End End of line Select to end Move to end
of line of module
Page Up Page up Select to top Top of current
of module procedure
Page Down Page down Select to end End of
of module current
procedure
Left Arrow Move cursor Extend Moves cursor
left selection 1 left 1 word
character left
Right Arrow Move cursor Extend Moves cursor
right selection 1 right 1 word
character
right
Up Arrow Move cursor Extend Previous
up selection up procedure
Down Arrow Move cursor Extend Next
down selection procedure
down
Space Complete Activate
word drop system menu
down

Tab Indent / Un-indent Cycle through Cycle


complete windows applications
word
Enter New line
Backspace Delete Delete to Undo
previous start of word
character

Please report any errors to https://exceloffthegrid.com/contact


Version 1.2

Visual Basic Editor – Shortcut Keys (Page 3)


On its own Shift Ctrl Alt Ctrl + Shift
A Select all Add-ins menu
C Copy
D Debug menu
E Export Edit menu
module
F Find File menu
G Immediate
window
H Replace Help menu
I Quick info Turn on list
parameter
info
J List available Insert menu Drop down of
properties constants
L Call stack
M Import file
N New line (no
indentation)
O Format menu
P Print
Q Close VBE
R Project Run menu
explorer
S Save
T Components Tools menu
dialog box
V Paste View Menu
W Window
Menu
X Cut
Y Cut entire line
Z Undo

Please report any errors to https://exceloffthegrid.com/contact

You might also like