2014-09-24 41 views
0

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

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 
+1

你相信哪条线在上面的代码保存单个细胞的范围是多少? – 2014-09-24 20:40:29

+0

这行是一个拼写错误:'Set rng1 = Sheet2.Cells.Range(“A2:A”&N)',应该是'Set rng2 = ...',对吧? – 2014-09-24 20:40:58

+0

没错。这两行将从第二行开始的范围一直保存到两张单独的工作表上的最后一个填充列。我想使用for循环,我开始写入每一行,并从每张表中进行比较。 – 2014-09-24 20:44:05

回答

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

所以,你也许可以简化为这一点,并避免使用rng1Rowrng2Row变量:

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