CELLS Property in VBA
CELLS Property....
This property can be used as an alternative to the absolute range property and is generally more flexible to work with, as variables are easier to pass into it.
There are two optional arguments:
Cells([row] [,column])
Leaving the arguments empty (no brackets), it will detect the current selection as the active range.
Adding an argument to either row or column with a number will refer to the co-ordination of the number passed.
Adding both arguments will explicitly locate the single cell’s co-ordinate.
'Examples of the Cells property
Sub CellsExample()
Cells.Clear 'clears active selection
Cells(1).Value = "This is A1 - row 1"
Cells(, 1).Value = "This is A1 - col 1"
Cells(1, 1).Value = "This is A1 - explicit"
Cells(3, 3).Value = "This is C3"
Cells(5, 3).Font.Bold = True
End Sub
Variables can be passed into the Cells property and then nested into the Rangeobject as in the following example: '
'Two InputBoxes for rows and columns
Sub CellsExample2()
On Error GoTo handler
Dim intRows As Integer
Dim intCols As Integer
intRows = CInt(InputBox("How many rows to populate?"))
intCols = CInt(InputBox("How many columns to populate?"))
'starts at cell A1 to the number of rows and columns passed
Range(Cells(1, 1), Cells(intRows, intCols)).Value = "X"
Exit Sub
handler:
'Error code is handled here...
End Sub
By wrapping a range property around two cell properties, the flexibility of passing variables becomes apparent.
Range(Cells(1, 1), Cells(intRows, intCols))
Error handlers and InputBox functions are covered later in this guide.
Thanks
- Vikas Verma's blog
- Login or register to post comments
- 4626 reads
Recent comments
5 years 41 weeks ago
6 years 27 weeks ago
6 years 39 weeks ago
6 years 42 weeks ago
6 years 43 weeks ago
6 years 48 weeks ago
7 years 4 weeks ago
7 years 5 weeks ago
7 years 5 weeks ago
7 years 5 weeks ago