简体   繁体   English

使用VBA比较一个范围内的单元格与另一个范围内的单元格

[英]Comparing cells of one range to another using vba

I am in a situation where I have to compare each cells of a particular column from Sheet1 to eache cells of a particular column of Sheet2. 我处于一种情况,我必须将Sheet1中特定列的每个单元格与Sheet2中特定列的每个单元格进行比较。 For example cells of Column B to be compared with cells of Column G of Sheet2 and when the cell matches then Column I and Column J of Sheet1 will be replaced with the value of Column G and Column H respectively... 例如,要比较Sheet2的B列的单元格与Sheet2的G列的单元格,并且当该单元格匹配时,Sheet1的I列和J列将分别替换为G列和H列的值。

I have done the following coding which is solving my issue... 我已经完成了以下编码,可以解决我的问题...

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

But this code is taking time and for large rows its getting hanged. 但是,这段代码需要花费时间,并且对于大行,它已被挂起。 I think storing the data in Array and comparing will take lesser time...on achieving this am trying the following code which is giving error: 我认为将数据存储在Array中并进行比较将花费更少的时间...要实现此目标,请尝试以下提供错误的代码:

    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

Can anyone please on this am stuck to this problem quiet a long 任何人都可以在这个问题上坚持很长时间

You can loop just through one sheet cells. 您可以仅循环通过一个工作表单元格。 For each cell do find on the other sheet. 对于每个单元格,请在另一张纸上找到。 Should be quicker. 应该更快。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM