通过滥用很容易做到MATCH
。
第一个过程只是验证测试,也是如何声明事物的示例(相反,如果您需要其他变量类型等,您必须更改哪些声明)。
Sub testCaller()
Dim testArr1() As Variant ' <~~ Variable type must match
Dim testArr2() As Variant ' the variable required in the
Dim testArr3() As Variant ' actual procedure
Dim testArr4() As Variant
testArr1 = Array("abc", "abc", "def", "abc", "asdf", "bcd")
testArr2 = Array("abc", "asdf")
Call listUniqueArrayContents(testArr1(), testArr2())
testArr3 = Array(1, 2, 3, 4, 5)
testArr4 = Array(1, 2)
Call listUniqueArrayContents(testArr3(), testArr4())
End Sub
Sub listUniqueArrayContents(arr() As Variant, arrCompare() As Variant)
Dim uniqueValues() As Variant
Dim mIndex As Variant
Dim j As Integer
j = 0
For i = 0 To UBound(arr())
' Reset the placeholder for our MATCH values
mIndex = Null
' Disable errors, otherwise you get popups every time there's a unique value
On Error Resume Next
' Call MATCH function
mIndex = Application.WorksheetFunction.match(arr(i), arrCompare(), 0)
' Restore normal error handling
On Error GoTo 0
If mIndex < 1 Or IsNull(mIndex) Then
' If match variable is Null, it means the value was unique
' So we'll write that value to a separate array to keep track of it
If j = 0 Then ReDim Preserve uniqueValues(0 To 0)
If j <> 0 Then ReDim Preserve uniqueValues(UBound(uniqueValues()) + 1)
uniqueValues(UBound(uniqueValues)) = arr(i)
j = j + 1
End If
Next i
Debug.Print "--Unique values:--"
For k = LBound(uniqueValues()) To UBound(uniqueValues())
Debug.Print uniqueValues(k)
Next k
Debug.Print "--End--"
End Sub
对于测试示例,它为您提供了预期的:
--唯一值:--
def
bcd
--End--
--唯一值:--
3
4
5
--End--
或者,您可以将其更改为 aFunction
并让它返回唯一值数组。
改变这个:
Sub listUniqueArrayContents(arr() As Variant, arrCompare() As Variant)
对此:
Function listUniqueArrayContents(arr() As Variant, arrCompare() As Variant) As Variant
并将最后一个For
循环替换为listUniqueArrayContents = uniqueValues()