VBA 2D 数组使用多个分隔符分割

问题描述 投票:0回答:2

目前我正在尝试使用不同的分隔符将文件分解为 2 列表,例如:

-5 Name1, +7 Octopus, -6 Name22, +5 Horse, -7 Name100, +3 Owl

我的最终结果应该是一个 2 列表,例如:

名字1章鱼
名称22马
名称100 猫头鹰

到目前为止我的代码相当简单:

Sub SplitText()

Dim TextString As String, WArray() As String, Counter As Integer, Strng As String

    TextSring = Range("A1").Value
    WArray() = Split(TextString, ",")

    For Counter = LBound(WArray) To UBound(WArray)

        Strng = WArray(Counter)
        Cells(Counter + 2, 1).Value = Trim(Strng)

    NextCounter

End Sub

非常需要您的帮助,谢谢:)

arrays excel vba 2d delimiter
2个回答
0
投票

下面的代码适用于您提供的字符串。我希望你的真实数据没问题。请参阅评论以获取解释。

Sub SplitText()
Dim s As String
Dim v
Dim i As Long, j As Long


s = "-5 Name1, +7 Octopus, -6 Name22, +5 Horse, -7 Name100, +3 Owl"

'let's remove space, pluses and minuses
s = Replace(Replace(Replace(s, " ", ""), "+", ""), "-", "")

'and cut by commas
v = Split(s, ",")

For i = 0 To UBound(v)
    If InStr(v(i), "Name") Then
        'remove numbers before names
        v(i) = "Name" & Split(v(i), "Name")(1)
    Else
        For j = 48 To 57
            'remove figures in animals
            v(i) = Replace(v(i), ChrW(j), "")
        Next j
    End If
Next i

For i = 0 To UBound(v) Step 2
    'see the results
    Debug.Print v(i) & " " & v(i + 1)
Next i
End Sub

0
投票

想象一下字符串:dataStr = "top-left-margin," & _ “名称-SpecialEffect-TextAlign,”&_ “font-32:粗体字体颜色,”&_ “BackColor-backStyle-borderStyle”

代码:

ReDim dataArr(nrOfOccurences(dataStr, ","))

产生结果: enter image description here 而下面的代码:

  For i = LBound(dataArr) To UBound(dataArr)
    dataArr(i) = Split(Split(dataStr, ",")(i), "-")
  Next

产生结果: enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.