The simplest way to refer to a single cell on the current Excel worksheet is simply to enclose the A1 form of its reference in square brackets:
[a3] = "Hello!"
Note that square brackets are just convenient syntactic sugar for the Evaluate
method of the Application
object, so technically, this is identical to the following code:
Application.Evaluate("a3") = "Hello!"
You could also call the Cells
method which takes a row and a column and returns a cell reference.
Cells(3, 1).Formula = "=A1+A2"
Remember that whenever you pass a row and a column to Excel from VBA, the row is always first, followed by the column, which is confusing because it is the opposite of the common A1
notation where the column appears first.
In both of these examples, we did not specify a worksheet, so Excel will use the active sheet (the sheet that is in front in the user interface). You can specify the active sheet explicitly:
ActiveSheet.Cells(3, 1).Formula = "=SUM(A1:A2)"
Or you can provide the name of a particular sheet:
Sheets("Sheet2").Cells(3, 1).Formula = "=SUM(A1:A2)"
There are a wide variety of methods that can be used to get from one range to another. For example, the Rows
method can be used to get to the individual rows of any range, and the Cells
method can be used to get to individual cells of a row or column, so the following code refers to cell C1:
ActiveSheet.Rows(1).Cells(3).Formula = "hi!"