简体   繁体   中英

multiple delimiters (words) in vba

How can multiple delimiters be used for the split() function? I want to use more than two words as the delimiters but I'm unsure how that is possible.

c = Trim(t.value)
arr = Split(c, "hello" , "hi")

You can replace the multiple words first using replace and then use that in split.

eg

mystring= Replace(mystring, "hello", "#")
mystring= Replace(mystring, "hi", "#")
mystring= Replace(mystring, "thanks", "#")
newstring= Split(mystring, "#")

you could go like follows:

Option Explicit

Sub main()
    Dim t As String
    Dim arr As Variant, seps As Variant, sep As Variant

    seps = Array("hello", "hi") '<--| define your seperators list

    t = "hello i would hello like to hi split this string hello with multiple hello separators hi" '<--| string to split

    t = " " & t & " " '<--| add trailing blank to catch possible "border" 'separators'
    For Each sep In seps
        t = Replace(t, " " & sep & " ", "|") 'turn all separators into one only
    Next sep
    t = Trim(t) '<--| remove trailing blanks
    If Left(t, 1) = "|" Then t = Right(t, Len(t) - 1) '<--| remove any initial 'separator'
    If Right(t, 1) = "|" Then t = Left(t, Len(t) - 1) '<--| remove any final 'separator'
    arr = Split(t, "|")

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.

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