Excel - 比较两个选项卡。将匹配移动到一个选项卡,将其他选项移动到另

时间:2016-11-16 18:00:10

标签: excel

我正在寻找一种方法来获取"政策号码"从选项卡B列A中比较一个"政策号码列表"在标签A栏A上。

如果发现将行复制到Tab C,如果没有将行复制到Tab D

列标题是

Policy#   Date   Amount   Carrier company

由于

1 个答案:

答案 0 :(得分:1)

试试这个:

Public Sub CopyRows()

    Dim ewbT As Workbook: Set ewbT = ThisWorkbook ' Change ewbT to target Workbook, maybe ActiveWorkbook
    Dim ewsA As Worksheet: Set ewsA = ewbT.Worksheets("A")
    Dim ewsB As Worksheet: Set ewsB = ewbT.Worksheets("B")
    Dim ewsC As Worksheet: Set ewsC = ewbT.Worksheets("C")
    Dim ewsD As Worksheet: Set ewsD = ewbT.Worksheets("D")

    Dim dctPolicy As Dictionary: Set dctPolicy = New Dictionary
    Dim r As Long: For r = 2 To ewsA.UsedRange.Rows.Count ' Change 2 to first row of data
        dctPolicy.Add ewsA.Cells(r, 1).Value, 0
    Next r

    For r = 2 To ewsB.UsedRange.Rows.Count ' Change 2 to first row of data
        Dim varTemp() As Variant: ReDim varTemp(0 To 0, 0 To 3)
        varTemp = ewsB.Cells(r, 1).Resize(1, 4).Value
        Dim ewsT As Worksheet: Set ewsT = ewsC
        If dctPolicy.Exists(ewsB.Cells(r, 1).Value) = False Then
            Set ewsT = ewsD
        End If
        ewsT.Cells(ewsC.UsedRange.Rows.Count + 1, 1).Resize(1, 4).Value = varTemp
    Next r

End Sub

请注意,您需要工具>参考文献>已启用Microsoft Scripting Runtime。