简体   繁体   English

如何在VBA excel上每n个字符分割一个字符串?

[英]How to split a string every nth character on VBA excel?

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, 是否可以在第10个字符后分割字符串,即

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 您可以使用Mid函数(类似于@Kemal Al GAZZAH答案)来轻松实现此目的,但是对循环使用Step选项而不是计算输出的数量

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 您也可以将其编写为Function ,以使其更加实用

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) 您可以使用此代码,它使用函数MID进行循环, 该函数从字符串(3个参数字符串,开始和长度)中检索n个字符。

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 下面的代码具有将strig作为参数拆分的一个函数,我将该字符串放入cell(1,2),结果从第1行开始,列在第1列中,您当然可以更改

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM