问题
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 there is two columns name and number and in sheet2 i have numbers along its other information like date, charging and etc.
Sheet 1
No Name PhoneNumber
1 Bob 7254
2 Cristin 5468
3 Luara 1234
Sheet2
No PhoneNumber Date Charged Name
1 1145 12/30/2014 2$
2 7254 11/26/2014 3$
3 2365 3/9/2014 7$
4 5468 3/10/2014
5 1234 3/11/2014
What i want is to compare PhoneNumber column of sheet2 (B column) with PhoneNumber column of sheet1 (C column) and if a matching is found then copy Name (B column) from Sheet1 into Name column of sheet2 (E column). If no match then the name column in sheet2 must be blank.
i have searched and found the below code and modified a bit but i am not sure whether it is correct or no:
Sub test()
Dim rng1 As Range, rng2 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)
If rng1.Value = rng2.Value Then
Range("B2:B" & TotalRows).Copy Destination:=Sheets("Sheet2").Range("E2")
End If
Set rng2 = Nothing
Next j
Set rng1 = Nothing
Next i
End Sub
Please help me as the time is so short for my this project and i will highly appreciate your assistance in this regard.
回答1:
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
来源:https://stackoverflow.com/questions/27700515/excel-2010-macro-to-compare-two-columns-for-finding-the-matched-value