在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
这些方法可以根据实际情况选择使用。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: VBA输入框InputBox怎么设置