2014-11-03 181 views
1

我處於必須將Sheet1中特定列的每個單元格與Sheet2特定列的eache單元格進行比較的情況。例如,列B的單元格與Sheet2的列G的單元格進行比較,並且當單元格匹配時,Sheet1的列I和列J將分別替換爲列G和列H的值...使用vba將一個範圍的單元格與另一個範圍的單元格進行比較

I已經完成了以下編碼,正在解決我的問題...

Dim ws1 As Worksheet 
Dim ws2 As Worksheet 

Set ws1 = Worksheets("Sheet1") 
Set ws2 = Worksheets("Sheet2") 

lastRowi = ws1.Cells(Rows.Count, "E").End(xlUp).Row 

For Each l In ws1.Range("E2:E" & lastRowi) 
    For Each c In ws2.Range("G2:G" & lastRowj) 
      If l.Cells.Value = c.Cells.Value And l.Cells.Value <> "" Then 
      l.Cells.Offset(0, 3).Value = c.Cells.Offset(0, -1).Value 
      l.Cells.Offset(0, 4).Value = c.Cells.Offset(0, 0).Value 
      l.Cells.Offset(0, 5).Value = c.Cells.Offset(0, 1).Value 

     End If 
    Next c 
Next l 

但是,此代碼需要時間和大行被吊死。我認爲存儲陣列中的數據,並比較需要較少的時間......在達到這正嘗試下面的代碼是給錯誤:

Dim arr As Variant 

arr = ws1.Range("B2:B" & lastRowi) 

Dim varr As Variant 
varr = ws2.Range("G2:G" & lastRowj) 



For Each l In arr 
    For Each c In varr 
      If l.Cells.Value = c.Cells.Value And l.Cells.Value <> "" Then 
      l.Cells.Offset(0, 3).Value = c.Cells.Offset(0, -1).Value 
      l.Cells.Offset(0, 4).Value = c.Cells.Offset(0, 0).Value 
      l.Cells.Offset(0, 5).Value = c.Cells.Offset(0, 1).Value 

     End If 
    Next c 
Next l 

任何人都可以請這個我堅持這個問題幽長

回答

0

您可以通過一個工作表單元進行循環。對於每個單元格在另一個表單上找到。應該更快。

Dim ws1 As Worksheet 
Dim ws2 As Worksheet 

Set ws1 = Sheets("Sheet1") 
Set ws2 = Sheets("Sheet2") 
lastRow1 = 14 
With ws1 
    For r = 2 To lastRow1 
     Set HitRange = Nothing 
     Set HitRange = ws2.Columns(7).Find(.Cells(r, 5).Value) 
     If Not HitRange Is Nothing And .Cells(r, 5).Value <> "" Then 
      .Cells(r, 6) = ws2.Cells(HitRange.Row, 6) 
      .Cells(r, 7) = ws2.Cells(HitRange.Row, 7) 
      .Cells(r, 8) = ws2.Cells(HitRange.Row, 8) 
     End If 
    Next 
End With 
相關問題