Consider the following VBA MWE
Sub test()
Dim rng As Range
Set rng = Range("A:A, C:C")
Dim rRow As Range
For i = 1 To 5
Set rRow = Intersect(rng, rng.Cells(i, 1).EntireRow)
rRow.Value = 1
rRow.Cells(, 2).Value = 2
Next
End Sub
Which produces an output that looks like this
1 2 1
1 2 1
1 2 1
1 2 1
1 2 1
As we can see, the line rRow.Value = 1
sets the cells in the first and third column to 1. Now, I can't get my head around why the rRow.Cells(1,2)
doesn't access the third column such that the output is
1 2
1 2
1 2
1 2
1 2
and leave the second column empty, since this appears to be what is happening in the line rRow.Value = 1
. Can someone explain this logic to me?
EDIT:
Commenting out the rRow.Cells(,2).Value = 2
such that the code reads
Sub test()
Dim rng As Range
Set rng = Range("A:A, C:C")
Dim rRow As Range
For i = 1 To 5
Set rRow = Intersect(rng, rng.Cells(i, 1).EntireRow)
rRow.Value = 1
'rRow.Cells(, 2).Value = 2
Next
End Sub
yields the following output
1 1
1 1
1 1
1 1
1 1
where columns A and C are filled with ones, and column B is left alone.
Using the
Range
orCells
property of aRange
object (rather than the more usualWorksheet
), provides a reference to a range relative to the top left cell of the original range. It is not in any way restricted to cells within that original range. Hence this:refers to the cell one column to the right and one row below A1. So does this:
Note that it still only refers to one cell, even though the original range was 10 cells.
Cells
works in exactly the same way (just as it does with aWorksheet
parent). So this:and this:
both refer to B2.