我使用数组作为表中不存在的值的列表。但是,有时相等的值输入两次。
我使用了一个简单的条件来避免当前值等于先前值,但是我似乎无法找到整体上重复值的解决方案。
If k > 0 Then
If arrA(k) = arrA(k - 1) Then
arrA(k) = ""
k = k - 1
End If
End If
答案 0 :(得分:0)
重复过滤方法
就本领域而言,我通过重复过滤演示了一种方法(即不使用字典或集合-您会在SO:-上找到许多 dict / coll 示例):
示例代码
此示例假定要检查字符串值是否重复(在重复过滤中以区分大小写的方式使用大小写敏感-参见vbBinaryCompare
函数中的参数Filter
)并匹配当前索引位置({{ 1}})。
idx
Debug.Print结果,如 Visual Basic编辑器(VBE)
Option Explicit ' declaration head of code module
Sub DupEx()
' Purpose: delete subsequent string duplicates in array
' Method: repeated filter function using match to get index position
' Site: https://stackoverflow.com/questions/54044235/vba-is-there-a-way-to-check-if-a-value-is-equal-to-any-value-inside-array
' Author: T.M. (https://stackoverflow.com/users/6460297/t-m)
Dim arrA(), i&, idx&, flt, searched
' example string values (change to wanted values)
arrA = Array("zero", "one", "two", "two", "three", "two", "four", "zero", "four", "three", "five", "five")
flt = arrA
Debug.Print "Original array counts " & UBound(flt) + 1 & " elements: " & Chr(34) & Join(flt, ", ") & Chr(34)
For i = LBound(arrA) To UBound(arrA)
searched = arrA(i) ' define search term
If UBound(Filter(flt, searched, True, vbBinaryCompare)) > 0 Then
'[1] change first occurrence of search term to temporary dummy (to avoid later deletion)
On Error Resume Next
idx = Application.Match(searched, flt, False) - 1 ' deduct 1 as match result is one based
flt(idx) = ChrW(&H2999) ' change to temporary dummy value
'[2] execute filter (3rd argument=False DELETES each subsequent search value in flt array)
' [Caveat: this example deletes partial string findings as well !]
flt = Filter(flt, searched, False, vbBinaryCompare)
'[3] restore first occurrence back to old value
flt(idx) = searched
End If
Next i
Debug.Print "Filtered array counts " & UBound(flt) + 1 & " elements: " & Chr(34) & Join(flt, ", ") & Chr(34)
'arrA = flt ' overwrite original array
End Sub