我们如何在MS Excel中执行常用集合操作(​​union,intersection,minus)?

例如,我有一个xls在哪里:

  • 列A具有属性A的项目列表
  • B列有物品B的列表

我需要以下内容:

  • 列C是A联盟B(A和B的独特项目)
  • D列是交集B(A&B的共同项目)
  • E栏是A减B(A项而不是B项)
  • B列减A列(B列不列A列)

使用SQL或Python对元素列表进行操作似乎很容易。 但如何在xls中做到这一点?

注意:它应该是一个自动化,最小的复制粘贴和点击。 例如,我不想在B下复制粘贴A,然后“消除重复”以获得A联合B.

那么,Microsoft Excel不处理内置的集合操作。 但是你可以使用MATCH函数和error handling来模拟VBA。

这里是我工作的代码(我认为你有第一行):

Sub set_operations() Dim i, j, rangeA, rangeB, rowC, rowD, rowE, rowF As Long Dim test1, test2 As Boolean rangeA = ActiveSheet.Range("A" & CStr(ActiveSheet.Rows.Count)).End(xlUp).Row() rangeB = ActiveSheet.Range("B" & CStr(ActiveSheet.Rows.Count)).End(xlUp).Row() rowC = 2 rowD = 2 rowE = 2 rowF = 2 test1 = False test2 = False test2 = False 'A union B On Error GoTo errHandler1 For i = 2 To rangeA If Application.Match(ActiveSheet.Cells(i, 1), ActiveSheet.Range("C:C"), 0) > 0 Then If test1 = True Then ActiveSheet.Cells(rowC, 3) = ActiveSheet.Cells(i, 1) rowC = rowC + 1 End If End If test1 = False Next i For j = 2 To rangeB If Application.Match(ActiveSheet.Cells(j, 2), ActiveSheet.Range("C:C"), 0) > 0 Then If test1 = True Then ActiveSheet.Cells(rowC, 3) = ActiveSheet.Cells(j, 2) rowC = rowC + 1 End If End If test1 = False Next j 'A intersection B For i = 2 To rangeA On Error GoTo errHandler2 If Application.Match(ActiveSheet.Cells(i, 1), ActiveSheet.Range("B:B"), 0) > 0 Then On Error GoTo errHandler1 If Application.Match(ActiveSheet.Cells(i, 1), ActiveSheet.Range("D:D"), 0) > 0 Then If test1 = True And test2 = False Then ActiveSheet.Cells(rowD, 4) = ActiveSheet.Cells(i, 1) rowD = rowD + 1 End If End If End If test1 = False test2 = False Next i 'A minus B For i = 2 To rangeA On Error GoTo errHandler2 If Application.Match(ActiveSheet.Cells(i, 1), ActiveSheet.Range("B:B"), 0) > 0 Then On Error GoTo errHandler1 If Application.Match(ActiveSheet.Cells(i, 1), ActiveSheet.Range("E:E"), 0) > 0 Then If test1 = True And test2 = True Then ActiveSheet.Cells(rowE, 5) = ActiveSheet.Cells(i, 1) rowE = rowE + 1 End If End If End If test1 = False test2 = False Next i 'B minus A For i = 2 To rangeB On Error GoTo errHandler2 If Application.Match(ActiveSheet.Cells(i, 2), ActiveSheet.Range("A:A"), 0) > 0 Then On Error GoTo errHandler1 If Application.Match(ActiveSheet.Cells(i, 2), ActiveSheet.Range("F:F"), 0) > 0 Then If test1 = True And test2 = True Then ActiveSheet.Cells(rowF, 6) = ActiveSheet.Cells(i, 2) rowF = rowF + 1 End If End If End If test1 = False test2 = False Next i errHandler1: test1 = True Resume Next errHandler2: test2 = True Resume Next End Sub