将整行定义为范围的语法

在Excel中,我可以将整个列定义为一个范围,并在该范围内寻址单个单元格,如下所示:

Sub headache() Dim r As Range Set r = Range("A:A") MsgBox r(1).Address & vbCrLf & r(2).Address End Sub 

如果我试图用整行做同样的事情:

 Sub headache2() Dim r As Range Set r = Rows(1) MsgBox r(1).Address & vbCrLf & r(2).Address End Sub 

我没有得到范围内的单个单元格。 我的解决方法是:

 Set r = Range(Cells(1, 1), Cells(1, Columns.Count)) 

我不能相信这是使范围最简单的方法………..任何build议?

您可以使用:

  Set r = Rows(1).Cells 

或者只是使用:

  MsgBox r.Cells(1).Address & vbCrLf & r.Cells(2).Address 

但是请注意,使用索引访问范围的范围(或单元格)属性绝不会仅限于该范围。

等于

 Set r = Range("A:A") 

将会

 Set r = Range("1:1") 

我很好奇,在Rory的答案上进行这些testing。 也许别人可以解释地址是相同的,并且计数是不同的。

 Sub test() Debug.Print Me.Range("A:A").Count '1048576 Debug.Print Me.Columns(1).Count '1 Debug.Print Me.Columns(1).Cells.Count '1048576 Debug.Print Me.Range("1:1").Count '16384 Debug.Print Me.Rows(1).Count '1 Debug.Print Me.Rows(1).Cells.Count '16384 'interseting to me since the counts are different but the addresses are the same Debug.Print Me.Range("1:1").Address '$1:$1 Debug.Print Me.Rows(1).Address '$1:$1 Debug.Print Me.Rows(1).Cells.Address '$1:$1 End Sub