vba求两个数组的差集
时间: 2023-09-16 16:12:51 浏览: 157
求数组的差集.cpp
在 VBA 中,可以通过循环遍历数组的方式求两个数组的差集,具体代码实现如下:
```
Sub Difference()
Dim arr1() As Variant, arr2() As Variant
Dim diff() As Variant
Dim i As Long, j As Long, k As Long
Dim isFound As Boolean
'定义两个数组
arr1 = Array(1, 2, 3, 4, 5)
arr2 = Array(3, 4, 5, 6, 7)
'初始化差集数组
ReDim diff(0 To UBound(arr1))
'求差集
k = 0
For i = 0 To UBound(arr1)
isFound = False
For j = 0 To UBound(arr2)
If arr1(i) = arr2(j) Then
isFound = True
Exit For
End If
Next j
If Not isFound Then
diff(k) = arr1(i)
k = k + 1
End If
Next i
'输出差集
ReDim Preserve diff(0 To k - 1)
For i = 0 To UBound(diff)
Debug.Print diff(i)
Next i
End Sub
```
在这个例子中,我们定义了两个数组 `arr1` 和 `arr2`,然后通过双重循环遍历两个数组,判断 `arr1` 中的元素是否在 `arr2` 中出现过,如果没有出现过,则将其加入到差集数组 `diff` 中。最后输出差集数组中的元素。
阅读全文