使用vba将一个范围的单元格与另一个范围进行比较

时间:2014-11-03 10:40:15

标签: vba excel-vba excel

我处于这样一种情况,我必须将Sheet1中特定列的每个单元格与Sheet2的特定列的eache单元格进行比较。例如,B列的单元格与Sheet2的G列单元格进行比较,当单元格匹配时,Sheet1的I列和J列将分别替换为G列和H列的值......

我做了以下编码,解决了我的问题......

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

任何人都可以请这个问题安静了很长时间

1 个答案:

答案 0 :(得分: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