vba删除数组中的重复元素
时间: 2023-09-25 16:16:54 浏览: 193
要删除VBA数组中的重复元素,可以使用循环和条件语句来实现。以下是一个示例代码:
Sub RemoveDuplicates()
Dim arr1 As Variant
Dim i As Long, j As Long, k As Long
arr1 = Array(1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 10) '示例数组
'遍历数组
For i = LBound(arr1) To UBound(arr1)
'检查当前元素是否为重复元素
For j = i + 1 To UBound(arr1)
If arr1(i) = arr1(j) Then
'将重复元素置为空字符串
arr1(j) = ""
End If
Next j
Next i
'创建新数组,仅包含非空元素
Dim newArr() As Variant
ReDim newArr(0 To UBound(arr1))
k = 0
For i = LBound(arr1) To UBound(arr1)
If arr1(i) <> "" Then
newArr(k) = arr1(i)
k = k + 1
End If
Next i
'输出结果
For i = LBound(newArr) To UBound(newArr)
Debug.Print newArr(i)
Next i
End Sub
这段代码首先遍历数组,检查每个元素是否为重复元素,若是则将其置为空字符串。然后根据非空元素创建一个新数组,并输出结果。注意,这里假设数组中的元素是数值型,如果数组中的元素是字符串型,需要将条件判断部分的arr1(i) = arr1(j)改为StrComp(arr1(i), arr1(j), vbTextCompare) = 0。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [VBA 如何删除数组里的某个元素](https://blog.csdn.net/xuemanqianshan/article/details/103633050)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文