Excel VBA /根据字符数将字符串拆分为列

时间:2019-06-14 12:39:39

标签: excel vba

我想分割一个41个字符的字符串,如下例所示: 01288D29424001190601AJGBGR1413190528SR117

根据字符数从左到右分成不同的列,我用于拆分字符串的常量字符数标准是:

  5     6     3    6    2   4    4     6    1 1  3

01288 D29424 001 190601 AJ GBGR 1413 190528 S R 117

上面的字符串将是我的最终结果,要考虑到每个空格都代表一个新列。

1 个答案:

答案 0 :(得分:2)

通过 L1 将字段宽度放置在 B1 中,将数据放置在 A2 中。然后在 B2 中输入:

=LEFT(A2,B1)

,然后在 C2 中输入:

=MID($A$2,SUM($B$1:B$1)+1,C$1)

并复制:

enter image description here

与VBA相同的逻辑:

Sub poiuyt()
    Dim s As String, arr(0 To 10) As String, i As Long
    Dim msg As String

    msg = ""
    s = "01288D29424001190601AJGBGR1413190528SR117"
    wdth = Array(5, 6, 3, 6, 2, 4, 4, 6, 1, 1, 3)
    strt = Array(1, 6, 12, 15, 21, 23, 27, 31, 37, 38, 39)

    For i = 0 To 10
        arr(i) = Mid(s, strt(i), wdth(i))
        msg = msg & vbCrLf & arr(i)
    Next i

    MsgBox msg
End Sub

enter image description here