1

How do I properly exit a recursive function and return a value in VBA?

I have this simple code to remove multiple spaces from a string:

Public Function RemoveMultipleSpaces(s As String) As String
    If InStr(1, s, "  ", vbTextCompare) > 0 Then
        Dim newS As String
        newS = Replace(s, "  ", " ")
        RemoveMultipleSpaces (newS)
    Else
        RemoveMultipleSpaces = s
        End
    End If
End Function

But depending on what I use to exit either End or Exit Function, I either get nothing returned or an empty string.

1 Answer 1

4

A proper recursive function doesn't need a specific exit condition. You just stop calling the function recursively, and it exits.

However, if you want to explicitly exit, you can use Exit Function.

Your mistake, however, is that when you make a recursive call, you need to return the result of the recursive call.

Public Function RemoveMultipleSpaces(s As String) As String
    If InStr(1, s, "  ", vbTextCompare) > 0 Then
        Dim newS As String
        newS = Replace(s, "  ", " ")
        RemoveMultipleSpaces = RemoveMultipleSpaces(newS)
    Else
        RemoveMultipleSpaces = s
    End If
End Function
Sign up to request clarification or add additional context in comments.

3 Comments

Your code modifies the byref s as well as returning the result. That is not what the OP had.
@GSerg Valid, adjusted it to not modify the byref. Note this leads to storing one copy of the string for each level of recursion, which can be a burden on memory when working with large strings.
Oh, that makes sense! Thank you.

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.