VBA Palindrome function

283 Views Asked by At

I created the following function to check wether a given word is a palindrome and send back true or false. However, the function return #NAME! . Hereby the code:

Option explicit
Public Function palindrome(txt As String) As Boolean
Dim xend As Long
Dim xstrt As Long
Dim i As Long

xend = Len(txt)
xstrt = 1

For i = 1 To xend \ 2
    If Mid(txt, xstrt, 1) <> Mid(txt, xend - i + 1, 1) Then
        palindrome = False
        Exit Function
    End If
    palindrome = True

Next i

End Function

Thank you in advance for your help.

1

There are 1 best solutions below

3
VBasic2008 On

Is Palindrome (UDF)

  • No need to loop, when there is StrReverse.
Function IsPalindrome(ByVal CheckString As String) As Boolean
    Dim S As String: S = LCase(Replace(CheckString, " ", ""))
    If S = StrReverse(S) Then IsPalindrome = True
End Function

Sub Test()
    Debug.Print IsPalindrome("Ana")
    Debug.Print IsPalindrome("Nurses Run")
    Debug.Print IsPalindrome("Madam")
End Sub
  • BTW, use a forward slash / to divide, instead of xstrt use i, remove the spaces from the string (or don't), convert all characters to the same case, and finally, palindrome = True needs to come after the loop has finished. Also, palindrome = False is redundant since palindrome is False by default.
Function palindrome(ByVal txt As String) As Boolean
    
    Dim S As String: S = LCase(Replace(txt, " ", ""))
    Dim sLen As Long: sLen = Len(S)
    
    Dim i As Long
    
    For i = 1 To sLen / 2
        If Mid(S, i, 1) <> Mid(S, sLen - i + 1, 1) Then Exit Function
    Next i
        
    palindrome = True

End Function