使用VBA与CSV的不同或唯一值

时间:2018-10-24 09:13:55

标签: excel vba excel-vba

今天,一个使用宏和Excel电子表格的朋友问我是否有办法将csv整数字符串转换为具有不同值的csv。我来自linq和花哨的huha的现代时代,我认为这将是直截了当的,但是在Google和SO没有出现之后,我花了很多时间提出自己的解决方案。我想知道是否有更好的解决方案。这是输入: “ 1,45,2,4,5,2,3,5” 预期产量: “ 1,45,2,4,5,3”

我会尽快发布解决方案,但我希望能听到更好的SO解决方案。

3 个答案:

答案 0 :(得分:3)

您可以以此为基础来进行操作-有一些步骤可以帮助证明我在评论中所说的内容-可能不是构建集合,然后将其转换为在msgbox中加入的数组您可以将其写入单元格-或对下游执行任何操作。这将减少对collectionToArray函数的需要。

或者,您可以使用数组来执行此操作,但是我发现集合更整洁。

Public Sub GetDistinctCommaSeparated()

Dim values As String
Dim valuesArr() As String
Dim DistinctCol As New Collection

' Get an array from the comma separated field
values = Range("A1").Value
valuesArr = Split(values, ",")

' get a distinct collection
Set DistinctCol = MakeCommaArrayDistinct(valuesArr)

' convert to array - and join (demonstration purposes)
MsgBox Join(CollectionToArray(DistinctCol), ",")


End Sub

Private Function MakeCommaArrayDistinct(valuesArr() As String) As Collection

Dim output As New Collection

 ' Loop through your array and push items to a secondary collection only if they are not already there
 For Each x In valuesArr
        If IsInCollection(CStr(x), output) <> True Then
          output.Add CStr(x)
        End If
    Next x

Set MakeCommaArrayDistinct = output

End Function

' Checks if the current item exists within the collection
Public Function IsInCollection(stringToBeFound As String, col As Collection) As Boolean

    Dim x As Variant

    ' Empty Collection
    If col.Count = 0 Then
        IsInCollection = False
        Exit Function
    End If

    ' Loop and Check
    For Each x In col
        If CStr(x) = stringToBeFound Then
            IsInCollection = True
            Exit Function
        End If
    Next x

End Function

' Used to convert the collection to an array to easily display in the msgbox - Demonstration only
Public Function CollectionToArray(myCol As Collection) As Variant

    Dim result  As Variant
    Dim cnt     As Long

    ReDim result(myCol.Count - 1)

    For cnt = 0 To myCol.Count - 1
        result(cnt) = myCol(cnt + 1)
    Next cnt

    CollectionToArray = result

End Function

输出;

enter image description here

答案 1 :(得分:3)

我会使用字典作为快速简便的方法。使用覆盖语法将值添加到字典以处理重复项。然后使用.Keys生成一个数组,您可以使用带分隔符Join的{​​{1}}作为字符串返回。

","

答案 2 :(得分:0)

这是我想出的解决方案

Function GetUnique(notUnique As String) As String

    ar = Split(notUnique, ",")
    Dim result As String
    Dim retVal As New Collection

    For Each a In ar
     If HasKey(retVal, a) Then
      ' do nothomg
     Else
      retVal.Add a, a
     End If
    Next
    result = ""
    For Each r In retVal
     result = result + r + ","
    Next

    GetUnique = Mid(result, 1, Len(result) - 1)

End Function

Function HasKey(coll As Collection, strKey) As Boolean
    Dim var As Variant
    On Error Resume Next
    var = coll(strKey)
    HasKey = (Err.Number = 0)
    Err.Clear
End Function