Marcos Foster
Marcos Foster

Reputation: 67

Recursive function returning empty string

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.

Upvotes: 1

Views: 345

Answers (1)

Erik A
Erik A

Reputation: 32642

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

Upvotes: 4

Related Questions