使用vba将一个范围的单元格与另一个范围的单元格进行比较
问题描述:
我处于必须将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
任何人都可以请这个我坚持这个问题幽长
答
您可以通过一个工作表单元进行循环。对于每个单元格在另一个表单上找到。应该更快。
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