0

Anybody have a good solution for recursive replace? For example, you still end up with commas in this string returned by MsgBox:

Dim s As String
s = "32,,,,,,,,,,,,,,,,23"

MsgBox Replace(s, ",,", ",")

I only want one comma.

Here is code that I developed, but it doesn't compile:

Function RecursiveReplace(ByVal StartString As String, ByVal Find As String, ByVal Replace As String) As String

    Dim s As String

    s = Replace(StartString, Find, Replace)
    t = StartString

    Do While s <> t
        t = s
        s = Replace(StartString, Find, Replace)
    Loop

RecursiveReplace = s
End Function

The compiler complains about the second line in the function:

s = Replace(StartString, Find, Replace)

It says Expected Array.

???

4
  • Can you confirm that the error reappears after you save your work, close everything including the host application (Excel or whatever you work with) and reopen again? Commented Jan 23, 2018 at 17:19
  • 2
    Replace is a function name. Maybe VBA thinks you are trying to call the function as the argument. Try with a different argument name? (Don't use Find/Replace as variable names is what I'm getting at) Commented Jan 23, 2018 at 17:20
  • @JacobH is right, overlooked that one. You cannot have a variable named Replace. Commented Jan 23, 2018 at 17:21
  • yes! thanks. there was also a mistake in my function, but that is the reason for the compile error.... Commented Jan 23, 2018 at 17:28

1 Answer 1

2

You can use a regular expression. This shows the basic idea:

Function CondenseCommas(s As String) As String
    Dim RegEx As Object
    Set RegEx = CreateObject("VBScript.RegExp")
    RegEx.Pattern = ",+"
    CondenseCommas = RegEx.Replace(s, ",")
End Function

Tested like:

Sub test()
    Dim s As String
    s = "32,,,,,,,,,,,,,,,,23"

    MsgBox CondenseCommas(s)
End Sub
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.