Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vba 访问行的两种方式之间的差异';s细胞_Vba_Excel - Fatal编程技术网

Vba 访问行的两种方式之间的差异';s细胞

Vba 访问行的两种方式之间的差异';s细胞,vba,excel,Vba,Excel,通过以下方式访问行的单元格有什么区别: 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).Add

通过以下方式访问行的单元格有什么区别:

   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

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

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

我稍微更改了您的过程,并添加了
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)
指的是相对于
aRow
的第2列,它是
C
,因为范围是从
B
开始的,而不是从
A
开始的

Cells(aRow.Row,2)
与写入
ActiveSheet.Cells(aRow.Row,2)
完全相同,并相对于
ActiveSheet
引用第2列,后者为
B
,因为工作表的范围从
A
开始

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

旁注:

我建议不要使用工作表并完全限定单元格/区域,这样您就可以始终看到单元格相对于哪个区域。

您的结果并不奇怪,因为
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()
)-这将给出相对于整个活动工作表的结果