Excel Compare two columns, copy matching rows to n

2019-08-12 16:32发布

问题:

I've been trying to do this for some time keep hitting a roadblock.

I have a sheet in Excel that has 5 columns with data: A,B,C,D & E.

I have another column F that has some data.

What I want is a formula or macro so that I can find all values from column F in column B, and copy only that entire row (A,B,C,D & E) into a new sheet (or just drop all other values).

I tried doing a formula and removing the error rows, but it messes the data up.

Any ideas?

回答1:

As i undestand you have data like following

Compare column C with B

A       B       C
Row 1   Value 1 Value 3
Row 2   Value 2 Value 5
Row 3   Value 3 Value 8
Row 4   Value 4 Value 3
Row 5   Value 5 Value 5
Row 6   Value 6 Value 8
Row 7   Value 7 Value 3
Row 8   Value 8 Value 5
Row 9   Value 9 Value 8

and you want result in sheet2

A       B
Row 3   Value 3
Row 5   Value 5
Row 8   Value 8

Try the following code

Sub Macro1()

    Dim Counter As Long

    Dim lastRow As Long
    lastRow = 10
    Dim arrColF(10) As String

    Sheets("Sheet1").Select

    For Counter = 1 To lastRow Step 1
        arrColF(Counter - 1) = Sheet1.Cells(Counter, 3).Value
    Next Counter

    arrStr = Join(arrColF, ", ")
    Dim strRange As String

    For Counter = 1 To lastRow Step 1
        If InStr(1, arrStr, Sheet1.Cells(Counter, 2).Value & ", ") > 0 Then
            strRange = strRange & "A" & Counter & ":B" & Counter
            If Trim(strRange) <> "" Then strRange = strRange & ","
        End If
    Next Counter
    strRange = Left(strRange, Len(strRange) - 1)

    Sheet1.Range(strRange).Select
    Selection.Copy
    Sheets("Sheet2").Select
    Range("A1").Select
    ActiveSheet.Paste

End Sub