VBA 字符串分隔符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15361574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 19:59:09  来源:igfitidea点击:

VBA String Delimiter

excelvbaexcel-vba

提问by Albertus

How can I split a string in VBA after a certain amount of the same delimiter?

如何在一定数量的相同分隔符后拆分 VBA 中的字符串?

For example : {"Josh","Green"},{"Peter","John"}.

例如:{"Josh","Green"},{"Peter","John"}

Here I would like {"Josh","Green"}as the first record in an array and {"Peter","John"}as the second. I want to avoid parsing the string character by character.

在这里,我想{"Josh","Green"}作为数组中的第一条记录和{"Peter","John"}第二条记录。我想避免逐个字符地解析字符串。

回答by Olle Sj?gren

There are several ways to do this, my suggestion:

有几种方法可以做到这一点,我的建议是:

Replace },{with something else before the split, to create a new delimiter.

},{在拆分之前替换为其他内容,以创建新的分隔符。

For example:

例如:

Option Explicit

Sub Test()
    Const c As String = "{""Josh"",""Green""},{""Peter"",""John""}"
    Dim s As String
    Dim v As Variant

    s = Replace(c, "},{", "}#,#{", 1)

    v = Split(s, "#,#")

    Debug.Print v(0)    '{"Josh","Green"}
    Debug.Print v(1)    '{"Peter","John"}
End Sub

That will split sinto a Variant-array vwith two strings, v(0)and v(1), instead of four strings, which you would get if you split the original string with just ,as a delimiter.

这将拆分sv包含两个字符串v(0)和的 Variant 数组v(1),而不是四个字符串,如果将原始字符串,作为分隔符拆分,则会得到四个字符串。