[英]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.