用逗号(,)拆分字符串,并将对象添加到集合中

时间:2018-03-13 12:54:56

标签: vba excel-vba excel

我有一个要求,我有一个大字符串。

例如:abc,def,ghi

我想分割这些字符串并将它们放在一个集合中。

必需输出:

ExampleCollection
abc
def
ghi

如何在VBA中执行此操作。

2 个答案:

答案 0 :(得分:5)

类似的东西:

Sub marine()
    Dim s As String, c As Collection
    Dim arr

    s = "abc,def,mbs"
    arr = Split(s, ",")
    Set c = New Collection

    For Each a In arr
        c.Add a
    Next a
End Sub

答案 1 :(得分:1)

我会这样做。

Sub SplitAll()
Dim xRg As Range
Dim xRg1 As Range
Dim xCell As Range
Dim I As Long
Dim xAddress As String
Dim xUpdate As Boolean
Dim xRet As Variant
On Error Resume Next
xAddress = Application.ActiveWindow.RangeSelection.Address
Set xRg = Application.InputBox("Please select a range", , xAddress, , , , , 8)
Set xRg = Application.Intersect(xRg, xRg.Worksheet.UsedRange)
If xRg Is Nothing Then Exit Sub
    If xRg.Columns.Count > 1 Then
    MsgBox "You can't select multiple columns", , "Kutools for Excel"
    Exit Sub
    End If
    Set xRg1 = Application.InputBox("Split to (single cell):", "Kutools for Excel", , , , , , 8)
    Set xRg1 = xRg1.Range("A1")
    If xRg1 Is Nothing Then Exit Sub
        xUpdate = Application.ScreenUpdating
        Application.ScreenUpdating = False
        For Each xCell In xRg
            xRet = Split(xCell.Value, ",")
            xRg1.Worksheet.Range(xRg1.Offset(I, 0), xRg1.Offset(I + UBound(xRet, 1), 0)) = Application.WorksheetFunction.Transpose(xRet)
            I = I + UBound(xRet, 1) + 1
        Next
        Application.ScreenUpdating = xUpdate
End Sub

有关所有信息,请参阅以下链接。

https://www.extendoffice.com/documents/excel/3341-excel-split-comma-separated-values.html