简体   繁体   中英

Excel VBA / Split String Into Columns based on Character Count

I would like to split a String of 41 Characters like the example below: 01288D29424001190601AJGBGR1413190528SR117

Into different columns based on character count from left to right, my constant character count criteria to split the string is:

  5     6     3    6    2   4    4     6    1 1  3

01288 D29424 001 190601 AJ GBGR 1413 190528 S R 117

The string above will be my end result, take into consideration that every space represent a new column.

Place your fieldwidths in B1 through L1 and data in A2 . Then in B2 enter:

=LEFT(A2,B1)

and in C2 enter:

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

and copy across:

在此处输入图片说明

Same logic for 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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM