vba: get unique values from array

前端 未结 9 2288
北恋
北恋 2020-11-22 15:30

Is there any built-in functionality in vba to get unique values from a one-dimensional array? What about just getting rid of duplicates?

If not, then how would I get

9条回答
  •  梦谈多话
    2020-11-22 16:00

    If the order of the deduplicated array does not matter to you, you can use my pragmatic function:

    Function DeDupArray(ia() As String)
      Dim newa() As String
      ReDim newa(999)
      ni = -1
      For n = LBound(ia) To UBound(ia)
        dup = False
        If n <= UBound(ia) Then
          For k = n + 1 To UBound(ia)
            If ia(k) = ia(n) Then dup = True
          Next k
    
          If dup = False And Trim(ia(n)) <> "" Then
            ni = ni + 1
            newa(ni) = ia(n)
          End If
        End If
      Next n
    
      If ni > -1 Then
        ReDim Preserve newa(ni)
      Else
        ReDim Preserve newa(1)
      End If
    
      DeDupArray = newa
    End Function
    
    
    
    Sub testdedup()
    Dim m(5) As String
    Dim m2() As String
    
    m(0) = "Horse"
    m(1) = "Cow"
    m(2) = "Dear"
    m(3) = "Horse"
    m(4) = "Joke"
    m(5) = "Cow"
    
    m2 = DeDupArray(m)
    t = ""
    For n = LBound(m2) To UBound(m2)
      t = t & n & "=" & m2(n) & " "
    Next n
    MsgBox t
    End Sub
    

    From the test function, it will result in the following deduplicated array:

    "0=Dear 1=Horse 2=Joke 3=Cow "

提交回复
热议问题