Question

I have a variable like this:

var = "word1 (should be replaced by word1)"

I need to get word1 by itself and sometimes it may be a word(s) but it will always have (*) after it. Any way to delete text between the () signs, then remove the (), then remove any space(s) after the last word?

Not sure of any way to go about it.

Was it helpful?

Solution

The simplest would be:

var = Trim(Mid(var, 1, InStr(var, "(") - 1))

InStr returns the index of the first occurrance of "(". I subtract 1 to discount the position held by the "(".

Mid cuts the string from the first character at position 1, to the index returned by the InStr.

Then Trim to remove trailing spaces.

OTHER TIPS

Like this?

Sub Sample()
    Dim sVar As String
    Dim MyAr() As String

    sVar = "word1 (should be replaced by word1)"

    MyAr = Split(sVar, "(")

    Debug.Print MyAr(0)
End Sub

EDIT

The above code can be shortened further

Sub Sample()
    Dim sVar As String
    sVar = "word1 (should be replaced by word1)"
    Debug.Print Split(sVar, "(")(0)
End Sub

I would use SPLIT function.

arrayVar2 = split(var, "(" )

You will now have an array with 2 elements.

Split the second element

arrayVar3 = split( arrayVar2[1], ")" )

Then join:

out = arrayVar2[0] & arrayVar3[1]

That will work as long as there is only ever a single set of brackets in the string.

The alternative way is to make use of the regular expression library but that is a longer answer. It wouldn't be as efficient but would be better if needing to handle more complex strings.


UPDATE: I went a bit further than the question perhaps called for. My solution ensures that the bracketed text is removed - any text AFTER the bracketed text is also retained.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top