获取整行excel vba

获取整行excel vba,vba,excel,Vba,Excel,我将行中的第一个单元格保存为一个范围,我只是想知道如何引入整行,以便能够比较这两个单元格。任何帮助都将不胜感激 Sub crossUpdate() Dim rng1 As Range, rng2 As Range, N As Long, C As Long N = Cells(Rows.Count, "A").End(xlUp).row Set rng1 = Sheet1.Cells.Range("A2:A" & N) C1 = rng1.Rows.Count Set rng1 = Sh

我将行中的第一个单元格保存为一个范围,我只是想知道如何引入整行,以便能够比较这两个单元格。任何帮助都将不胜感激

Sub crossUpdate()
Dim rng1 As Range, rng2 As Range, N As Long, C As Long
N = Cells(Rows.Count, "A").End(xlUp).row
Set rng1 = Sheet1.Cells.Range("A2:A" & N)
C1 = rng1.Rows.Count
Set rng1 = Sheet2.Cells.Range("A2:A" & N)
C2 = rng2.Rows.Count
For i = 2 To C


End Sub

我注意到您的代码中有一个输入错误,正如您双重分配给rng1变量的注释所示,请将第二个更改为设置rng2=

你有一个从i=2到C的循环,但是你从来没有给变量C分配过任何东西,所以这不会导致错误,但是它将无法完成你希望它能做的事情

Option Explicit 'use this to force variable declaration, avoids some errors/typos
Sub crossUpdate()
'Declare each variable separately, it is easier to read this way and won't raise problems
' in some cases if you need to pass to other subs/functions
Dim rng1 As Range
Dim rng2 As Range
Dim N As Long

'Add these declarations
Dim C As Long
Dim R as Long
'I deleted declarations for i (replaced with R), C, N which won't be needed. And also C1, C2

'I'm going to declare some additional range variables, these will be easier to work with
Dim rng1Row as Range
Dim rng2Row as Range
Dim cl as Range

N = Cells(Rows.Count, "A").End(xlUp).row
Set rng1 = Sheet1.Cells.Range("A2:A" & N)

Set rng2 = Sheet2.Cells.Range("A2:A" & N)  'This line was incorrect before


'Now to compare the cells in each row

For R = 2 to rng1.Rows.Count
    Set rng1Row = rng1.Cells(R,1).EntireRow
    Set rng2Row = rng2.Cells(R,1).EntireRow

    For C = 1 to rng1.Columns.Count
        If rng1Row.Cells(R,C).Value <> rng2Row.Cells(R,C).Value Then
            'Do something if they are NOT equal
        Else
            'Do something if they ARE equal
        End If
    Next

End Sub
这会引起错误吗?毕竟,[A1]是一个单细胞。它不会引发错误,而是正确地打印:$B$1

因此,您可以简化为这样,并避免使用rng1Row和rng2Row变量:

For R = 2 to rng1.Rows.Count
    For C = 1 to rng1.Columns.Count
        If rng1.Cells(R,C).Value <> rng2.Cells(R,C).Value Then
            'Do something if they are NOT equal
        Else
            'Do something if they ARE equal
        End If
    Next
End Sub

您认为上面代码中的哪一行将单个单元格保存为范围?这一行是一个输入错误:Set rng1=Sheet2.Cells.RangeA2:a&N,应该设置为rng2=…,对吗?对。这两行将从第二行开始一直保存到两张单独的图纸上最后填充的列的范围。我想用我开始写的for循环,把每一行都写进去,并从每张纸上比较它们。好的,给我一秒钟,我现在正在写答案:
For R = 2 to rng1.Rows.Count
    For C = 1 to rng1.Columns.Count
        If rng1.Cells(R,C).Value <> rng2.Cells(R,C).Value Then
            'Do something if they are NOT equal
        Else
            'Do something if they ARE equal
        End If
    Next
End Sub