问题
I stumbled across some unexpected behavior when writing an answer for this question.
When chaining together Range calls, Address always returns the address of the very first Range object in the statement. For example:
Public Sub Unexpected()
Debug.Print Range("B3").Address
Debug.Print Range("B3").Range("A1").Address
End Sub
Returns the following output.
$B$3
$B$3
But I would have expected it to return the Address of the last Range object in the chain.
$B$3
$A$1
Can anyone explain this behavior? Preferably with a quote of and link to the appropriate documentation.
回答1:
There is documentation on using Range().Cells() which indicates that Cells() will return the location within the given Range() relative to the top left cell of the Range(). Testing this theory with Range().Range() gives:
Public Sub Unexpected()
Debug.Print Range("B1:C3").Range("A1").Address
'$B$1
Debug.Print Range("B1:C3").Range("B1").Address
'$C$1
End Sub
Documentation here:
When applied to a
Rangeobject, the property is relative to theRangeobject.For example, if the selection is cell
C3, thenSelection.Range("B1")returns cellD3because it’s relative to theRangeobject returned by theSelectionproperty. On the other hand, the codeActiveSheet.Range("B1")always returns cellB1.
来源:https://stackoverflow.com/questions/27828134/why-does-range-address-return-the-address-of-the-first-cell-when-chained