從vba中的陣列中間洗掉一個專案
我回圈遍歷兩個陣列以查找 Arr1 中的哪一項等于 Arr2。然后我想從 Arr1 中洗掉該專案。最后,我會將 Arr1 添加到 Arr2。所以,它以某種方式檢測 Arr1 是否有不在 Arr2 中的新專案,并將該專案添加到 Arr2
Public Sub cmpArr()
For i =LBound(Arr1) To UBound(Arr2)
For j = LBound(Arr2) To UBound(Arr2)
If Arr1(i) = Arr2(j) Then
'Arr1(i) delete
End If
Next j
Next i
End Sub
用戶 braX 建議使用字典。在他的建議下,我將使用陣列改為使用字典。這是代碼
Public Sub comp_2Dictnries()
For i =0 To dict1.Count -1
For j=0 To dict2.Count -1
On Error Resume Next
If dict1.Items()(i) =dict2.Items()(j) Then
dict1.Remove dict1.Keys()(i)
End If
Next j
Next i
End Sub
uj5u.com熱心網友回復:
請嘗試下一種方法:
Sub replaceArrayElem()
Dim arr1, arr2, arr3, mtch, i As Long, j As Long
arr1 = Array("a", "c", "d", "jj", "t", "www")
arr2 = Array("m", "r", "o", "c", "uu", "n", "d")
For i = LBound(arr2) To UBound(arr2)
mtch = Application.match(arr2(i), arr1, 0)
If IsNumeric(mtch) Then 'if a match exists
arr1(mtch - 1) = "#$@!": arr1 = filter(arr1, "#$@!", False) 'filter eliminate a specific element
End If
Next i
Debug.Print Join(arr1, ",") ' just to visually see how arr1 remained
arr3 = arr2: ReDim Preserve arr3(UBound(arr2) UBound(arr1) 1)
For i = UBound(arr2) 1 To UBound(arr3)
arr3(i) = arr1(j): j = j 1
Next i
Debug.Print Join(arr3, ",") 'the returned array...
End Sub
請在測驗后發送一些反饋。
和一個使用 a 的版本Scripting.Dictionary
(如果你有陣列,或者喜歡使用它們):
Sub replaceArrayElemDict()
Dim arr1, arr2, arr3, mtch, i As Long, j As Long
Dim dict As Object
arr1 = Array("a", "c", "d", "jj", "t", "www")
arr2 = Array("m", "r", "o", "c", "uu", "n", "d")
Set dict = CreateObject("Scripting.Dictionary")
For i = LBound(arr2) To UBound(arr2)
dict(arr2(i)) = vbNullString
Next i
For i = LBound(arr1) To UBound(arr1)
dict(arr1(i)) = vbNullString 'it creates a NEW dictionary key only if it does not exist...
Next i
Debug.Print Join(dict.Keys, ",") 'the returned array...
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/536522.html
標籤:数组VBA重复