Index of range with multiple non-sequential column

2019-07-13 03:29发布

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.

1条回答
不美不萌又怎样
2楼-- · 2019-07-13 03:55

Using the Range or Cells property of a Range object (rather than the more usual Worksheet), 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:

Range("A1").Range("B2")

refers to the cell one column to the right and one row below A1. So does this:

Range("A1:A10").Range("B2")

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 a Worksheet parent). So this:

Range("A1").Cells(2, 2)

and this:

Range("A1:A10").Cells(2, 2)

both refer to B2.

查看更多
登录 后发表回答