简体   繁体   中英

Split string by character and keep before and after string

I have string containing numbers. These numbers are coordinates for scientific modeling.

I need to split this string by character "-" to partial string "before" and "after".

This works only for static number of digit (character).

Dim str As String
Dim before As String
Dim after As String

str = "3-525"
before= Left(str, InStr(str, "-") - 1) ' =3
after= Right(str, InStr(str, "-") + 1) ' =525

If input is str = "3-525" output is before = 3 and after = 525
But when it comes to str = "15-50" output is before = 15 and after = 5-50 and is annoying to retype it again and again.

I need some dynamic solution to split these coordinates by "-" character.

Use Split :

Sub Test()
    Dim str As String
    str = "3-525"
    
    Dim x
    x = Split(str, "-")
    
    Debug.Print x(0) '<--- this is "before", or 3
    Debug.Print x(1) '<--- this is "after", or 525
End Sub

Of course applying Split() is the most evident way to execute a split operation. - Nevertheless your original code logic to count from an Instr() finding isn't wrong per se and you need not reject the way you form the after variable completely.

(1) Using the Right() function only needs a length as further argument, not a position . So you might calculate the remaining length to the right as difference between the total length and the "-" character and modify your code to

 after = Right(s, Len(s) - InStr(s, "-"))

(btw I'd prefer s to your str variable as I don't want to mix it up with VBA's Str() function) .

(2) Alternatively you could use the Mid() function and code as follows:

 after = Mid(s, InStr(s, "-") + 1)

Here it suffices to pass a starting position as further argument (without need to indicate a total lenght in addition).

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