我有两个(非空)数组(变体)和数字。我想列出第一个数组中的所有数据,而不是第二个数组。
Dim existingWorkerIDs() As Variant
Dim newWorkerIDs() As Variant
For Each temp In newWorkerIDs
If existingWorkerIDs.contains(temp) Then
...do sth...
End If
Next temp
有可能吗?
答案 0 :(得分:0)
滥用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
对于测试示例,它给出了预期的结果:
- 唯一值: -
高清
BCD
--End--
- 独特的价值观: -
3
4
5
--end -
或者,您可以将其更改为Function
并让它返回唯一值数组。
改变这个:
Sub listUniqueArrayContents(arr() As Variant, arrCompare() As Variant)
到此:
Function listUniqueArrayContents(arr() As Variant, arrCompare() As Variant) As Variant
并将最后一个For
- 循环替换为listUniqueArrayContents = uniqueValues()