简体   繁体   中英

Use macro to compare column in two Excel worksheets and add matches to third sheet

I just need to be able to match if id numbers in the "A" column of sheet 1 match in the respective "A" column of sheet 2, and just paste the matches to column "A" in sheet 3. The column range in sheet 1 is not the same range as sheet 2, and sheet 3 needs to have the matches pasted in each row as they are found (ie no blank rows in between). I DO NOT need to do anything about numbers that do not match.

I have attempted to modify code from a different thread. It catches some matches, but not all. I guess the ranges are incorrect but I don't really know how to code that in VBA. Plus there are spaces in the column where some of the other duplicates should be posted. The "if found is nothing then x = 0" is unnecessary (and may even be causing the aforementioned error), but if I take that out I get a type mismatch error.

Sub matchPAs()

Dim x, i, total, fRow As Integer
Dim found As Range

total = Sheets(1).Range("A" & Rows.Count).End(xlUp).Row

For i = 1 To total
    match1 = Worksheets(1).Range("A" & i).Value
 Set found = Sheets(2).Columns("A:A").Find(what:=match1)
If found Is Nothing Then
    x = 0
Else
    fRow = Sheets(2).Columns("A:A").Find(what:=match1).Row
    Worksheets(3).Range("A" & i).Value = Worksheets(1).Range("A" & fRow).Value

 End If
Next i

End Sub

the logic is a little off:

Sub matchPAs()
    Dim total As Long
    total = Sheets(1).Range("A" & Rows.Count).End(xlUp).Row

    Dim i As Long
    For i = 1 To total
        Dim match1 As Variant
        match1 = Worksheets(1).Range("A" & i).Value

        Dim found As Range
        Set found = Sheets(2).Columns("A:A").Find(what:=match1)
        If Not found Is Nothing Then
            Worksheets(3).Range("A" & Rows.Count).End(xlUp).Offset(1).Value = match1
        End If
    Next i
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM