我将行中的第一个单元格保存为范围,我只是想知道如何引入整行,以便我可以比较两者。任何帮助将不胜感激。
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
答案 0 :(得分:0)
我注意到您的代码中存在拼写错误,正如您在rng1
变量中重复分配的评论所示,将第二个更改为Set rng2 = ...
你有一个循环For i = 2 to 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
实际上有一些更简单的方法可以做到这一点,但为了演示的目的,我更容易通过这样分解来解释。但是,例如,范围不受它们包含的单元数量的限制。考虑一下:
Debug.Print Range("A1").Cells(,2).Address
这是否会引发错误?毕竟,[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