Excel macro to copy data from one sheet to another based on specific matching conditions

后端 未结 1 839
无人及你
无人及你 2021-01-25 23:22

I have two sheets, one of which contains data for all of the match codes (Master Sheet) and another that contains data for only some match some codes. These codes link to a data

相关标签:
1条回答
  • 2021-01-26 00:07
    1. Build a dictionary of match codes and filter on those.
    2. Copy everything filtered over to the second worksheet.
    3. Remove duplicates based on match code and data number.
    4. [optional] Sort the new data.

    BTW, your original code shows Sheet 2, not Sheet2.

    Option Explicit
    
    Sub same_old_same_old()
        Dim ws1 As Worksheet, ws2 As Worksheet
        Dim d As Long, dMNUMs As Object
    
        Set ws1 = ActiveWorkbook.Worksheets("Master Sheet")
        Set ws2 = ActiveWorkbook.Worksheets("Sheet 2")
        Set dMNUMs = CreateObject("Scripting.Dictionary")
        dMNUMs.CompareMode = vbBinaryCompare
    
        '1. Build a dictionary of match codes and filter on those.
        With ws2
            For d = 2 To .Cells(Rows.Count, "A").End(xlUp).Row
                dMNUMs.Item(CStr(.Cells(d, "A").Value2)) = .Cells(d, "E").Value2
            Next d
        End With
    
        '2. Copy everything filtered over to the second worksheet.
        With ws1
            If .AutoFilterMode Then .AutoFilterMode = False
            With .Cells(1, 1).CurrentRegion
                .AutoFilter Field:=1, Criteria1:=dMNUMs.keys, Operator:=xlFilterValues
                With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
                    If CBool(Application.Subtotal(103, .Cells)) Then
                        .Cells.Copy _
                          Destination:=ws2.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
                    End If
                End With
            End With
            If .AutoFilterMode Then .AutoFilterMode = False
        End With
    
        '3. Remove duplicates based on match code and data number.
        '4. [optional] Sort the new data
        With ws2
            If .AutoFilterMode Then .AutoFilterMode = False
            With .Cells(1, 1).CurrentRegion
                .RemoveDuplicates Columns:=Array(1, 5), Header:=xlYes
                .Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _
                            Key2:=.Columns(5), Order2:=xlAscending, _
                            Orientation:=xlTopToBottom, Header:=xlYes
                End With
        End With
    
        dMNUMs.RemoveAll: Set dMNUMs = Nothing
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题