[英]Comparing cells of one range to another using vba
我处于一种情况,我必须将Sheet1中特定列的每个单元格与Sheet2中特定列的每个单元格进行比较。 例如,要比较Sheet2的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
但是,这段代码需要花费时间,并且对于大行,它已被挂起。 我认为将数据存储在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
任何人都可以在这个问题上坚持很长时间
您可以仅循环通过一个工作表单元格。 对于每个单元格,请在另一张纸上找到。 应该更快。
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.