使用宏比较匹配列并将其复制到下一列

时间:2016-06-10 09:46:59

标签: vba excel-vba macros excel-2010 excel

我刚接触宏并遇到问题。好吧,我在网上得到了一个比较两张纸的宏文件,并将找到的匹配复制到第一行。

Sub test()
Dim rng2 As Range, c2 As Range, cfind As Range
Dim x, y
With Worksheets("sheet1")
    Set rng2 = Range(.Range("B2"), .Range("B2").End(xlDown))
    For Each c2 In rng2
        x = c2.Value
        With Worksheets("sheet2").Columns("b:B")
            On Error Resume Next
            Set cfind = .Cells.Find(what:=x, lookat:=xlWhole)
             If cfind Is Nothing Then GoTo line1
             y = cfind.Offset(0, -1).Value
        End With
        c2.Offset(0, -1) = y
line1:
    Next c2
End With

End Sub

但是我不明白它是如何正常工作的?我的意思是我只想扭转现有的逻辑。我的意思是我想将下一行中找到的匹配填充到C列中不在A中的数据。

我尝试修改它不起作用的偏移索引值。任何人都可以帮我解决这个问题。

谢谢!

1 个答案:

答案 0 :(得分:1)

Sub test()
Dim rSh1 As Range, rSh2 As Range, rFound As Range, r As Range

With Worksheets("sheet1")
    Set rSh1 = .Range("B2", .Range("B2").End(xlDown))
End With

With Worksheets("sheet2")
    Set rSh2 = .Columns("b:B")
End With

For Each r In rSh1
    With r
        Set rFound = rSh2.Find(what:=.Value, lookat:=xlWhole)
        If Not rFound Is Nothing Then
            .Offset(0, 1) = rFound.Offset(0, -1).Value
        End If
    End With
Next r

End Sub