簡體   English   中英

除非第n個字符=“”,否則如何在VBA上每第n個字符分割字符串?

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

我有一個類似於

 "1111 2222222 3333 77777 44444 55555 6666 99999"

是否可以在每個第10個字符之后拆分字符串,而不拆分子字符串(通過subtrings,我的意思是“ 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

我認為將字符串拆分成數組並從此處進行測試會更好。

這樣的事情(完全沒有優化,但是效果很好):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM