Você está na página 1de 3

VBA CHEAT SHEET 1 - Workbooks and Ranges

USEFUL PROPERTIES

WORKBOOK
thisWorkbook

Workbook that contains the code

Workbooks(Book1.xlm) An open workbook called Book1.xlm


ActiveWorkbook

WORKSHEET
A Worksheet is a member of a Workbook
Sheet called Sheet1

.Worksheets(2)

Second Sheet of workbook.

ActiveWorksheet

Current active worksheet. Avoid this.

RANGE AND CELLS


Range and Cells are members of a Worksheet
.Range(A1)

Cell A1

.Range(A1:A5)

Range of Cells A1:A5

.Range(A1:A5).Offset(2)

Offset 2 Rows. Range of Cells A3:A7

.Range(A1:A5).Offset(,2)

Offset 2 Cols. Range of Cells C1:C5

.Cells(1,1)

Cell at Row 1, Column 1 i.e. A1

Returns Worksheet

.Worksheets(1).Parent

Returns Workbook

.Range(A1).Parent.Parent Returns Workbook

Current active workbook. Avoid this.

.Worksheets(Sheet1)

.Range(A1).Parent

Worksheets(1).Name

Worksheet name

Workbook..Name

Workbook file name

Workbook.Path

Folder of the workbook

Application.UserName

Current user of Excel

MAIN VARIABLE DATA TYPES


Long: +/- 2,147,483,647
Integer: +/- 32,767
Currency has 4 decimals places
Currency +/- 922,337,203,685,477.5808
Double has more than 4 decimal places
Double: +/- 4.94065645841247E-324 to
1.79769313486232E308
Date: 1/1/100 to 31/12/9999 and times 0:00:00 to
23:59:59
String: Approx 2 billion characters of text

.Range(.Cells(1,1),.Cells(5,1)) Range of Cells A1:A5


USING WORKBOOKS, SHEETS AND RANGES
Put 7 in cell A1 on worksheet Sheet1 of this workbook
thisWorkbook.Worksheets(Sheet1).Range(A1) = 7
Put 7 in cell A1 on worksheet Sheet1 of this workbook
thisWorkbook.Worksheets(Sheet1).Cells(1,1) = 7
Put 7 in cell B1 to B5 on worksheet Sheet1 of this workbook
thisWorkbook.Worksheets(Sheet1).Range(B1:B5) = 7
USING WITH
The With keyword means you only need to write the object once
With thisWorkbook.Worksheets(Sheet1)
.Range(A1) = 7
.Cells(1,2) = 55
.Range(.Cells(1,1),.Cells(5,5)) = 67.77
Debug.Print .Name
End With

USING VARIABLES WITH CELLS


Declare
Dim val As Long,
Dim sText As String
Place value in a variable
Val = 5
sText = John Smith
Place value from a worksheet cell in a variable
Val = .Range(A5)
sText = .Cells(1,1)
Place value in cell(s)
.Range(A1:A5) = Val
.Cells(1,1) = Val
.Range(B2:B3) = sText
Increase value of variable by 1
Val = Val + 1

GO THROUGH ALL WORKSHEETS


Dim sheet As Worksheet
For Each sheet in thisWorkbook.Worksheets
Display name in intermediate window (Ctrl + G to view)
Debug.Print sheet.Name
Next sheet

OPEN WORKBOOK
Dim wrk As Workbook
Set wrk = Workbooks.Open (C:\docs\book.xlsm)
Do something with workbook
wrk.Worksheets("sheet1").Range("A1") = 55
wrk.Close SaveChanges:=True

Excel Macro Mastery

VBA CHEAT SHEET 2 Arrays and Collections


STATIC ARRAY
Declare static array with size
Dim arrMarks(0 To 5) As Long

COLLECTION and DICTIONARY


These are similar. A good rule of thumb is
Use a Collection when
1. You need to run through every item in a list.
2. Your list may have duplicates

Set all values to default e.g. 0


Erase arrMarks

Use a Dictionary when


1. You need to access individual items in a list
2. Your list will not have duplicates

DYNAMIC ARRAY
Declare dynamic array
Dim arrMarks() As Long

COLLECTION
Declare and create
Dim coll As New Collection

Set size allocate memory


ReDim arrMarks(1 To 10)
Deallocate memory
Erase arrMarks

Add Item can be any data type


coll.Add Apple
Access Item 1
Debug.Print Coll(1)
Remove Item 1
Coll.Remove 1

STATIC\DYNAMIC ARRAY
Add value
arrMarks(0) = 56
arrMarks(5) = 100
Go through all items in array
For i= LBound(arrMarks) To UBound(arrMarks)
Debug.Print arrMarks(i)
Next i

Display all items using For Each


Dim element as variant
For Each element In coll
Debug.Print element
Next element

ARRAY AND RANGE


' Create array
Dim arrMarks() As Variant

Remove all items


For i = coll.Count to 1 Step 1
Coll.Remove i
Next i

' Read values into 2D array from Range


arrMarks= .Range("A1:Z2").Value

DICTIONARY
Add Project Reference Microsoft Scripting Runtime

' Write values to Range from 2D array


.Range("A3:Z4").Value = arrMarks

Declare and Create


Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")

2D ARRAY
' Create array
Dim arrMarks(2,4) As Long
' Read values into 2D array from Range
arrMarks= .Range("A1:Z2").Value
Go through all items in 2D array
Dim i As Long, j As Long
For i = LBound(arrMarks) To UBound(arrMarks)
For i = LBound(arrMarks,2) To UBound(arrMarks,2)
Debug.Print arrMarks(i,j)
Next j
Next j

Add item - sKey must not already exist in dictionary


dict.Add Apples, 50
Access Item stored at Key i.e. print 50
Debug.Print Dict(Apples)
Check item exists
If dict.Exists(Apples) Then
Loop through all items
For Each key In dict.keys
Debug.Print dict(key)
Next
Remove all items
dict.RemoveAll

Excel Macro Mastery

VBA CHEAT SHEET 3 - VBA Constructs


SUB
1. Can be called by a Button or Macro
2. Cannot return a value

IF THEN STATEMENT
If val = 1 Then
Debug.Print "One"
ElseIf val >= 2 Or val <= 3 Then
Debug.Print "Two or Three"
ElseIf val > 100 Then
Debug.Print "Greater than 100"
Else
Debug.Print "Other"
End If

Call on sub from another


Public Sub Process()
CreateReport 99, "John"
End Sub
Public Sub CreateReport(val As Long, sCust As String)
.Range(A1) = sCust
.Range(B1) = val
End Sub
FUNCTION
1. Cannot be called by a Button or Macro
2. Can return a value
3. Appears in Worksheet Function list
Get a value from the function CreateString
Public Sub Process()
Dim sName As String
Use parenthesis around arguments
sName = CreateString ("John",Smith)
End Sub

SELECT CASE STATEMENT


Select Case val
Case 1: Debug.Print "One"
Case 2 To 3: Debug.Print "Two or Three"
Case Is > 100: Debug.Print "Greater than 100"
Case Else: Debug.Print "Other"
End Select

USEFUL STRING FUNCTIONS


Dim sCustomer As String
sCustomer = John Smith

Returns a string
Public Function CreateString (sFirst As String, sLast As String)
CreateString = sFirst + + sLast
End Sub
EXIT TYPES
Exit Do

Exit a Do Loop

Exit For

Exit a For Loop

Exit Sub

Exit a Sub procedure

Exit Function

Exit a Function procedure

Returns 4 Left chars : John


Left(sCustomer,4)
Returns 5 Right chars : Smith
Right(sCustomer,5)
Returns 3 chars at position 6: Smi
Mid(sCustomer,6,3)
Reverses String: htimS nhoJ
StrReverse(sCustomer)
Replaces Smith with Burke: John Burke
Replace(sCustomer,Smith,Burke)
Finds position of first S in String: 6
Instr(sCustomer,S)
Converts to upper case: JOHN SMITH
UCase(sCustomer)
Converts to lower case: john smith
LCase(sCustomer)
Converts a number to a string data type

VBA LOOPS
Loop

How it Works

Example

For Next

You specify how many times you want it to run

For Each Next

Iterates through Collections of items e.g. Worksheets

Do While Loop

Runs 0 or more times until a condition is met

Do Loop While

Run 1 or more times until a condition is met

Do Until .. Loop

Runs 0 or more times until a condition is met

Do Loop Until

Run 1 or more times until a condition is met

While Wend

Runs 0 or more times until a condition is met


Excel Macro Mastery

For i = 1 to 10
Next i
For Each sheet in .Worksheets
Next sheet
Do While i < 10
Loop
Do
Loop While i < 10
Do Until i >= 10
Loop
Do
Loop Until i >= 10
While i < 10
Wend

Você também pode gostar