我试图回答这个问题当我在 Excel 中遇到一些奇怪的 VBA 行为时。我写了一个非常简单的子程序来演示这个问题:
Sub debugAddresses(rng As Range)
Debug.Print "Whole range: " & rng.Address
Dim i As Long
For i = 1 To rng.Cells.Count
Debug.Print rng.Cells(i).Address
Next i
End Sub
我循环遍历范围对象中的每个单元格并打印其地址,很简单吧?
debugAddresses Range("B2:B3")
' Result as expected:
' >> Whole range: $B$2:$B$3
' >> $B$2
' >> $B$3
然而,对于不连续的范围,我得到一些奇怪的行为:
debugAddresses Range("A1,B2")
' Strange behaviour when getting addresses of individual cells:
' >> Whole range: $A$1,$B$2
' >> $A$1
' >> $A$2
有人能解释一下吗?具体来说why the Cells
对象,可用于索引连续范围,似乎只是扩展第一个选定的Area
.
编辑:可能值得注意的是,使用For Each
循环遍历实际单元格范围对象给出预期结果*
Sub debugAddresses2(rng As Range)
Debug.Print "Whole range: " & rng.Address
Dim c As Range
For Each c In rng
Debug.Print c.Address
Next c
End Sub
*See my answer for a comment on a more robust solution, as this (apparently) may not always give the expected result