除非nth character =“”,否则如何在VBA上每n个字符拆分一个字符串?

时间:2019-03-27 15:05:27

标签: excel vba

我有一个类似于

的字符串
 "1111 2222222 3333 77777 44444 55555 6666 99999"

是否可以在第10个字符之后分割字符串,而不分割子字符串(通过子字符串,我的意思是“ 1111”,“ 3333”等),

1111
2222222 
3333 77777 
44444 
55555 6666
99999

我已经尝试过了,但这并不完全正确。谢谢

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

1 个答案:

答案 0 :(得分:4)

我认为将字符串拆分为数组并从那里进行测试会更好。

类似这样的东西(完全没有优化,但是效果很好):

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

输出:

1111
2222222
3333 77777
44444
55555 6666
99999