vba兩集合的交、並、補集
阿新 • • 發佈:2019-02-10
有兩列資料A、B,求出A有B沒有、B有A沒有、AB都有、AB的合集:
用VBA是的字典來做:
Sub 字典法()
Dim arr1()
arr1 = Range("A2:b31").Value
Set d = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(arr1)
d(arr1(i, 1)) = 1
Next
For j = 1 To UBound(arr1)
d(arr1(j, 2)) = d(arr1(j, 2)) + 2
Next
ReDim arr1(1 To d.Count, 1 To 4)
i = 0: j = 0: l = 0
For Each d1 In d.keys
If d(d1) = 1 Then 'A有B沒有
j = j + 1
arr1(j, 1) = d1
ElseIf d(d1) = 2 Then 'B有A沒有
l = l + 1
arr1(l, 2) = d1
Else 'AB都有
i = i + 1
arr1(i, 3) = d1
End If
r = r + 1
arr1(r, 4) = d1 'AB的合集
Next
Range("d2").Resize(d.Count, 4) = arr1
End Sub