Excel 2010 Macro to compare two columns for finding the matched value

拜拜、爱过 提交于 2019-12-02 09:20:11

Looks like you were almost there. Your copy line needed a little tweaking, however. In the example below, I added an additional variable called rngName, to store the range of the name to be copied and assigned it a value in the for j loop. if the numbers match (i.e. rng1.value = rng2.value) it will copy the range containing the name to the associated row in sheet 2. Notice that I used .Range ("E" & i) for the copy-to range. The copy-to range in your example would always drop the name in the same cell as its always assigned to "E2". Also, you have a variable called TotalRows that had no value. It must have meant something in the original code you copied it from, so I got rid of that too. Try this and let me know how it works for you.

Sub test()
 Dim rng1 As Range, rng2 As Range, rngName As Range, i As Integer, j As Integer
    For i = 1 To Sheets("Sheet2").Range("B" & Rows.Count).End(xlUp).Row
        Set rng1 = Sheets("Sheet2").Range("B" & i)
        For j = 1 To Sheets("Sheet1").Range("C" & Rows.Count).End(xlUp).Row
            Set rng2 = Sheets("Sheet1").Range("C" & j)
            Set rngName = Sheets("Sheet1").Range("B" & j)
            If rng1.Value = rng2.Value Then
                rngName.Copy Destination:=Worksheets("Sheet2").Range("E" & i)
            End If

        Set rng2 = Nothing
    Next j
    Set rng1 = Nothing
 Next i
End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!