访问行的单元格的两种方式之间的差异

访问行的单元格有什么区别:

Sub test6() Dim wRange As Range Set wRange = Range("B3:P10") For Each aRow In wRange.Rows 'need to get this row's second column (B) Cells(aRow.Row, 4).value = aRow.Cells(1, 2).Address Cells(aRow.Row, 5).value = Cells(aRow.Row, 2).Address Next End Sub 

我得到奇怪的结果,取决于范围。 除此之外,我还有一个更复杂的程序,当使用这两种方法时,结果也会有所不同。

我改了一下你的程序,并添加了Debug.Print的输出作为注释,以更好地解释为什么这是一个预期的结果:

 Option Explicit 'in the first line of your modules: Ensures you need to declare all variables Sub test6() Dim wRange As Range, aRow As Variant Set wRange = Range("B3:P10") For Each aRow In wRange.Rows ' Outputs of the first loop run: Debug.Print aRow.Address ' $B$3:$P$3 Debug.Print aRow.Cells(1, 2).Address ' $C$3 Debug.Print Cells(aRow.Row, 2).Address ' $B$3 Next End Sub 

说明
aRow是原始范围B3:P10中只包含一行的子范围( $B$3:$P$3 )(但不是假设的整个工作表行),所以aRow.Cells(1, 2)指的是第2列相对于aRow ,它是C因为范围是从B开始而不是A

Cells(aRow.Row, 2)与写入ActiveSheet.Cells(aRow.Row, 2)并且指向与ActiveSheet相关的第2列,因为表单的范围是从A开始A

aRow.EntireRow.Cells(1, 2).Address将与Cells(aRow.Row, 2).Address相同Cells(aRow.Row, 2).Address因为现在我们引用从A列开始的整个行。

边注:
我build议不要假设工作表并完全限定您的细胞/范围,以便您始终能够看到细胞相对于哪个范围。

你的结果并不奇怪,因为aRow.Cells().Address返回一个地址,相对于B列,因为wRange第一列也是B。

所以在你的情况下,你需要这条线:

  ... 'need to get this row's second column (B) Cells(AROW.Row, 4).Value = AROW.Cells(1, 1).Address '^ relative index ... 

而当你使用这个属性没有对象限定符(简单的Cells() ) – 这给你一个相对于整个活动工作表的结果!

RowIndex和ColumnIndex参数是相对偏移量 。

单元格(aRow.Row,4)是指ActiveSheet的单元格。 aRow.Cells(1,2)是指aRow范围内的单元格。