VBA Cheat Sheet v1.2
VBA Cheat Sheet v1.2
VBA Cheat Sheet v1.2
Version 1.2
Opening workbooks
Open a workbook
Workbooks.Open ("C:\FilePath\Name.xlsx")
Save workbooks
Save a workbook
wb.Save
Active a workbook
wb.Activate
'Hidden
Worksheets("SheetName").Visible = xlSheetHidden
'Invisible
Worksheets("SheetName").Visible = xlSheetVeryHidden
'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
Comparison operators
= Equal to
<> Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
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
'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
Add Names
Create Name with workbook scope
wb.Names.Add Name:="myNamedRange", _
RefersTo:="=Sheet1!$C$1:$D$5"
Delete a Name
Delete Name
If name macthes will delete workbook and worksheet Names
wb.Names("myNamedRange").Delete
Change a Name
Change name and Refers to of a Name
nm.Name = "changedMyNamedConstant“
nm.RefersTo = "=50%"
Remove AutoFilter
ws.AutoFilterMode = False
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
Filter on no color
ws.Range("$A$1").AutoFilter Field:=1,_
Operator:=xlFilterNoFill
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
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")
'Method 2
Dim srs As Series
Set srs = cht.SeriesCollection("Series Name")
Error bars
'Turn error bars on/off
srs.HasErrorBars = True
srs.HasErrorBars = False
Points
Reference points
Dim srs As Series
Dim pnt As Point
Save selection
Selection.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=pdfFile
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
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, "\")
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