Excel VBA,如何在Excel中获得两张MINUS或EXCEPT效果?

时间:2017-06-18 12:56:58

标签: excel vba excel-vba

我有一张三张工作簿。 Sheet1看起来像这样:

enter image description here

Sheet2如下所示:enter image description here

我想要的是Sheet2的子集。在Sheet2中,如果{1}}(列A)出现在Sheet1列A中,则将其从最终结果中删除。所以我的预期结果是:enter image description here

如何使用VBA或纯Excel技术完成此任务?您可以从此处下载我的测试工作簿:https://www.dropbox.com/s/n5dbzf3uwna2dwv/Excel%20VBA%2C%20how%20can%20I%20get%20the%20MINUS%20or%20EXCEPT%20effect%20for%20two%20sheets%20in%20Excel.xlsx?dl=1

1 个答案:

答案 0 :(得分:1)

对我来说,使用VBA更容易。

Sub CreateSubSet()

    Dim WsS As Worksheet                    ' Source
    Dim WsT As Worksheet                    ' Target
    Dim WsR As Worksheet                    ' Reference
    Dim Ref As Range                        ' the Id column in WsR
    Dim Id As Variant                       ' Id lifted from WsS
    Dim Fnd As Range                        ' Find Id in Ref
    Dim Rl As Long                          ' last row (in WsS)
    Dim Rs As Long                          ' Source row
    Dim Rt As Long                          ' Target row
    Dim C As Long                           ' column loop counter

    Set WsS = Worksheets("Sheet2")
    Set WsT = Worksheets("Result")
    Set WsR = Worksheets("Sheet1")

    With WsT
        Rt = .Cells(.Rows.Count, 1).End(xlUp).Row           ' 1 = column A
        Rt = Application.Max(Rt, 2)                         ' start in row 2
    End With

    With WsR
        Rl = .Cells(.Rows.Count, 1).End(xlUp).Row           ' 1 = column A
        Set Ref = .Range(.Cells(2, 1), .Cells(Rl, 1))       ' start in row 2
    End With

    With WsS
        Rl = .Cells(.Rows.Count, 1).End(xlUp).Row           ' 1 = column A
        For Rs = 2 To Rl                                    ' start in row 2
            Id = .Cells(Rs, 1).value
            Set Fnd = Ref.Find(Id, Ref.Cells(Ref.Cells.Count))
            If Fnd Is Nothing Then
                For C = 1 To 2
                    WsT.Cells(Rt, C).value = .Cells(Rs, C).value
                Next C
                Rt = Rt + 1
            End If
        Next Rs
    End With
End Sub