Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split( "TEXT" , "+" OR "-" ,2)

Tags:

split

vba

I need to separate a string with Visual Basic.

The downside is that i have more then one separator.

One is "+" and the other one is "-".

I need the code to check for the string if "+" is the one in the string then use "+"

if "-" is in the string then use "-" as separator.

Can I do this?

For example: Split( "TEXT" , "+" OR "-" ,2)

like image 992
AnteseN Avatar asked Mar 05 '26 22:03

AnteseN


2 Answers

easiest way is to replace out the second character and then split by only one:

Dim txt As String, updTxt As String
Dim splitTxt() As String

updTxt = Replace(txt, "-", "+")

splitTxt = Split(updTxt, "+")

or more complex. The below returns a collection of the parts after being split. Allows you to cusomize the return data a bit more if you require:

Dim txt As String, outerTxt As Variant, innerTxt As Variant
Dim splitOuterTxt() As String
Dim allData As New Collection

    txt = "test + test - testing + ewfwefwef - fwefwefwf"

    splitOuterTxt = Split(txt, "+")

    For Each outerTxt In splitOuterTxt

        For Each innerTxt In Split(outerTxt, "-")

            allData.Add innerTxt

        Next innerTxt

    Next outerTxt
like image 191
InContext Avatar answered Mar 08 '26 16:03

InContext


What you describe seems pretty straightforward. Just check if the text contains a + to decide which separator you should use.

Try this code:

dim separator as String

separator = Iif(InStr(txt, "+") <> 0, "+", "-")

splitResult = Split(txt, separator, 2)

The code assumes that the text you want to split is in the txt variable.

Please note that I don't have VBA here and wasn't able to actually run the code. If you get any error, let me know.

like image 25
Cristian Lupascu Avatar answered Mar 08 '26 15:03

Cristian Lupascu