我有两个数组,其中包含字符串值。让我们考虑下面的例子。
- 阵列 1:计算机科学、人工智能
- 阵列 2:Eclipse、MS、RAD、Linux、人工智能
我需要在我的两个数组中找到重复的数量。在上述情况下,我需要将总重复值设为 1(因为人工智能同时在 Array1 和 Array2 中)。有没有办法在 VBA 中做到这一点?
此函数假定 arr2 是一维数组:
Function ArrDupCount(ByVal arr1 As Variant, ByVal arr2 As Variant) As Long
Dim varElement As Variant
Dim lMatch As Long
On Error Resume Next
For Each varElement In arr1
lMatch = 0
lMatch = WorksheetFunction.Match(varElement, arr2, 0)
If lMatch > 0 Then ArrDupCount = ArrDupCount + 1
Next varElement
On Error GoTo 0
End Function
要使用它:
Sub tgr()
Dim arr1 As Variant
Dim arr2 As Variant
arr1 = Array("Computer science", "Artificial Intelligence")
arr2 = Array("Eclipse", "MS", "RAD", "Linux", "Artificial Intelligence")
MsgBox ArrDupCount(arr1, arr2) ' => 1
End Sub