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

前端 未结 1 1121
清酒与你
清酒与你 2021-01-25 20:47

I am very new to Excel macros and VBA, kindly help me please with my below situation. Here is the situation, i have two sheets (sheet1 and sheet 2) in sheet1 th

相关标签:
1条回答
  • 2021-01-25 21:31

    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
    
    0 讨论(0)
提交回复
热议问题