Repeated filtering method
Just for the sake of the art, I demonstrate an approach via ► repeated filtering (i.e. without using a dictionary or collection - you'll find numerous dict/coll examples at SO :-):
Example code
This example assumes string values to be checked for duplicates (using case sensitivity in repeated filtering in a tricky way - cf. argument vbBinaryCompare
in Filter
function) and matching the current index position (idx
) of each search term.
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
Debug.Print result as shown in the immediate window of the Visual Basic Editor (VBE)
Original array counts 12 elements: "zero, one, two, two, three, two, four, zero, four, three, five, five"
Filtered array counts 6 elements: "zero, one, two, three, four, five"