excel 如何在VBA中删除数组中的重复项并将它们连接起来

hi3rlvi2  于 2023-02-14  发布在  其他
关注(0)|答案(1)|浏览(112)

我有一个数组an VBA strname=[英语,科学,社会,英语,社会,科学,社会,英语,,,]
我想删除这个数组中的重复值和空值,并将它们连接起来。* 预期输出:英语;科学;社会 *
我尝试使用循环逻辑,但它不起作用

For i=0 to 10
 if strname[i] <> "" then
   if strname[i]= strname[i+1] then 
       tempstr=strname[i]
   end i
 end if
next

这里它将检查0与1,1与2,就像这样。我正在尝试正确的解决方案

bpzcxfmw

bpzcxfmw1#

请尝试下一种方法:

Sub removeArrDuplAndEmpty()
   Dim x As String, arr, i As Long, dict As Object
   
   x = "English,science,Social,English,Social,science,science,Social,English,,,"
   Set dict = CreateObject("Scripting.Dictionary")
   arr = Split(x, ",") 'extract the array
   
   For i = 0 To UBound(arr)
        If arr(i) <> "" Then dict(arr(i)) = 1 'create unique keys for non blank array elements
   Next 

   arr = dict.keys 'place back the dictionary keys in the initial array
   Debug.Print Join(arr, ";") 'only to visually see the result
End Sub

下一个版本按照您在问题中显示的方式处理字符串:

Sub removeArrDuplAndEmptyBis()
   Dim x As String, arr, i As Long, dict As Object
   
   x = "[English,science,Social,English,Social,science,science,Social,English,,,]"
   Set dict = CreateObject("Scripting.Dictionary")
   arr = Split(left(Mid(x, 2), Len(Mid(x, 2)) - 1), ",")
   
   For i = 0 To UBound(arr)
        If arr(i) <> "" Then dict(arr(i)) = 1
   Next i
   arr = dict.keys
   Debug.Print Join(arr, ",")
End Sub

这是你想要的吗?如果不是,请给出一个例子你真正的字符串它在处理后的样子...

相关问题