2014-09-24 64 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