简体   繁体   中英

How to split a string every nth character on VBA, unless nth character = “ ”?

I have a string similar to

 "1111 2222222 3333 77777 44444 55555 6666 99999"

Is it possible to split the string after each 10th character, without splitting the sub-strings (by subtrings I mean the "1111", "3333" etc),

1111
2222222 
3333 77777 
44444 
55555 6666
99999

I have tried this, but it's not quite right. Thanks

Dim i As Long, n As Long
Dim SplitStr, check_10th, TestStr As String
Dim string_length As Double

TestStr = Cells(1, 1)
n = 10

For i = 1 To Len(TestStr) Step n
    check_10th = Mid(TestStr, n, 1)
    If check_10th <> " " Then
        For k = 1 To 10 
            check_10th = Mid(TestStr, n - k, 1)
        If check_10th = " " Then
            Exit For
        End If

    Next k

    SplitStr = SplitStr & Mid(TestStr, i, n - k) & vbNewLine
Else
    SplitStr = SplitStr & Mid(TestStr, i, n) & vbNewLine
End If

Next i

Cells(2, 1).Value = SplitStr

I think you would be a lot better off here splitting your string into an array and testing from there.

Something like this (totally not optimized, but it works fine):

Sub test()
    Dim somestring As String
    Dim word As Variant
    Dim outline As String
    Dim outstring As String

    somestring = "1111 2222222 3333 77777 44444 55555 6666 99999"

    For Each word In Split(somestring, " ")
        If Len(outline & " " & word) <= 10 Then
            outline = Trim(outline & " " & word)
        Else
            If outstring = "" Then outstring = outline Else outstring = outstring & vbCrLf & Trim(outline)
            outline = word
        End If
    Next

    outstring = outstring & vbCrLf & Trim(outline)

    Debug.Print outstring
End Sub

Outputs:

1111
2222222
3333 77777
44444
55555 6666
99999

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