Common Data Types: Integer, Long, Double, String, Boolean, Date, Variant (can hold any type)
๐ Object References
Working with Worksheets & Ranges
' Reference current workbook
Set wb = ThisWorkbook
' Reference specific worksheet
Set ws = wb.Worksheets("Sheet1")
' Reference cells
Set rng = ws.Range("A1:C10")
Set cell = ws.Cells(1, 1) ' Row 1, Column 1
' Set values
ws.Range("A1").Value = "Hello"
ws.Cells(2, 1).Value = 123
Key Point: Use Set for objects, regular = for values
๐ Control Structures
Loops & Conditionals
' For Loop
For i = 1 To 10
Cells(i, 1).Value = i * 2
Next i
' If Statement
If Range("A1").Value > 10 Then
MsgBox "Greater than 10"
ElseIf Range("A1").Value = 10 Then
MsgBox "Equals 10"
Else
MsgBox "Less than 10"
End If
' While Loop
While Range("A1").Value < 100
Range("A1").Value = Range("A1").Value + 1
Wend
๐ง Procedures
Subs vs Functions
' Sub procedure (doesn't return value)
Sub HelloWorld()
MsgBox "Hello, World!"
End Sub
' Function (returns a value)
Function AddNumbers(a As Double, b As Double) As Double
AddNumbers = a + b
End Function
' Calling procedures
Call HelloWorld
result = AddNumbers(5, 3)
Functions return values, Subs perform actions
๐ Excel Integration
Common Excel Operations
' Using Excel functions in VBA
result = Application.WorksheetFunction.Sum(Range("A1:A10"))
average = Application.WorksheetFunction.Average(Range("B:B"))
' Working with ranges
Range("A1:C1").Font.Bold = True
Range("A1").Interior.Color = RGB(255, 255, 0)
' Copying and pasting
Range("A1:A10").Copy
Range("B1").PasteSpecial xlPasteValues