Read VBA as objects, properties and methods
Write VBA9 minPremium
Builds on Read and edit a macro in the VB Editor.
A finance assistant in Graz keeps the department budget in a workbook for each quarter, with a sheet for each month. At the start of a month she clears the last month's figures from the new sheet and writes its title, and she wants a macro for it.
How it works
VBA works on objects, the things you see in Excel, and they sit inside one another. Excel holds workbooks, a workbook holds worksheets, and a worksheet holds cells. A dot goes one level down, so a line names the cells it works on the way an address names a house.
| Level | In code | |
|---|---|---|
| 1 | Excel | Application |
| 2 | Workbook | Workbooks("Q1.xlsm") |
| 3 | Worksheet | Worksheets("March") |
| 4 | Cells | Range("B4") |
- Step 1: Excel itself, at the top, holds every open workbook.
- Step 2: One workbook, by its file name, holds its worksheets.
- Step 3: One sheet in that workbook, by its tab name, holds its cells.
- Step 4: One cell or block on that sheet: here B4.
Range( "B4") on its own means B4 on the sheet you're looking at.Leave out the outer levels and VBA uses the active ones: Range( is B4 on the active sheet of the active workbook.
A property is something an object has, such as a cell's Value, NumberFormat or Interior.Color. Set it with an equals sign: Range(. A method is something an object does, such as ClearContents or AutoFit. It takes no equals sign: Range(.
Example
Sub StartMarch() Worksheets("March"). Range( "C2:C25"). ClearContents Worksheets("March"). Range( "A1"). Value = "Budget for March" End Sub
To try a single line, press CtrlG in the editor to open the Immediate window, type the line and press Enter: VBA runs it at once. Start with a question mark to see a value, as in ?Range(. On a Mac, choose View > Immediate Window.
Common mistakes
Range(. A fill color belongs to the cells' interior, so VBA stops with "Object doesn't support this property or method". Write"A1:E1").Color = vbYellow Range(."A1:E1").Interior.Color = vbYellow - An equals sign after a method, as in
Range(. A method is an action, so it takes no equals sign:"B5:B20").ClearContents = True Range(."B5:B20").ClearContents - Text without quotes, as in
Range(. VBA reads Budget as the name of an empty variable and clears A1. Put text in double quotes."A1").Value = Budget
In short
- Objects sit inside one another, and a dot goes one level down: workbook, worksheet, range.
- A property is set with
=; a method runs without one. - Name the sheet, as in
Worksheets(, to work on cells without selecting them."March").Range( "A1")
Practice
Premium4 exercises: 3 macros and 1 quiz question.
Practice is part of Premium
Every lesson is free to read, and you can practice the free lessons without an account. This lesson's exercises are part of Premium, which you add to a free account.
Have one? Sign in