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, ie,
1111 22222
22 3333 77
777 44444
55555 6666
99999
You can achieve this quite easily using the Mid
function as similar to @Kemal Al GAZZAH answer but using the Step
option for the loop instead of calculating the number of outputs you'd have
Sub test()
Dim TestStr
Dim i As Long, n As Long
Dim SplitStr As String
TestStr = "1111 2222222 3333 77777 44444 55555 6666 99999"
n = 10
For i = 1 To Len(TestStr) Step n
SplitStr = SplitStr & Mid(TestStr, i, n) & vbNewLine
Next i
MsgBox SplitStr
End Sub
You could also write this as a Function
which would make it a lot more usable
Option Explicit
Public Function SplitString(StringToSplit As String, n As Long) As String()
Dim i As Long, arrCounter As Long
Dim tmp() As String
ReDim tmp(0 To CLng(Len(StringToSplit) / n))
For i = 1 To Len(StringToSplit) Step n
tmp(arrCounter) = Mid(StringToSplit, i, n)
arrCounter = arrCounter + 1
Next i
SplitString = tmp
End Function
Public Sub test()
Dim TestStr As String
TestStr = "1111 2222222 3333 77777 44444 55555 6666 99999"
MsgBox Join(SplitString(TestStr, 10), vbNewLine)
End Sub
You can use this code it uses a loop using the function MID which retreives n caratcters from a string (3 paramaetres string, start and length)
The below code has one function with the strig to split as parameter I putted this string in cells(1,2) and the results in column 1, starting from row 1: You can change that of course
Sub splitstring(mystring)
n = Int(1 + Len(s) / 10)
mystring1= mystring
For i = 0 To n
mystring1= Mid(mystring, 1 + i * 10, 10)
Cells(i + 1, 1) = mystring1
Next
End Sub
Sub call_me()
'splitstring ("1111 2222222 3333 77777 44444 55555 6666 99999")
splitstring (Cells(1, 2))
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.