CELLS Property in VBA

Vikas Verma's picture

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