在VBA中,可以使用以下幾種方法來實現數組去重:
Dim arr() As Variant
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
' 假設arr是要去重的數組
For Each element In arr
dict(element) = 1
Next element
' 通過轉換字典的鍵為數組
arr = dict.keys
Dim arr() As Variant
Dim col As New Collection
Dim element As Variant
' 假設arr是要去重的數組
For Each element In arr
On Error Resume Next
col.Add element, CStr(element)
On Error GoTo 0
Next element
' 使用RemoveDuplicates方法去重
RemoveDuplicates col
' 將Collection對象轉換為數組
ReDim arr(1 To col.Count)
For i = 1 To col.Count
arr(i) = col(i)
Next i
Sub RemoveDuplicates(col As Collection)
Dim i As Long
For i = col.Count To 2 Step -1
If col(i) = col(i - 1) Then
col.Remove (i)
End If
Next i
End Sub
Dim arr() As Variant
Dim newArr() As Variant
Dim i As Long, j As Long
Dim isDuplicate As Boolean
' 假設arr是要去重的數組
ReDim newArr(1 To UBound(arr))
j = 1
For i = 1 To UBound(arr)
isDuplicate = False
For k = 1 To j - 1
If arr(i) = newArr(k) Then
isDuplicate = True
Exit For
End If
Next k
If Not isDuplicate Then
newArr(j) = arr(i)
j = j + 1
End If
Next i
' 將newArr截斷為實際去重后的數組
ReDim Preserve newArr(1 To j - 1)
arr = newArr
這些方法可以根據實際情況選擇使用。