2

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.

Ike
  • 9,580
  • 4
  • 13
  • 29
Bobo31
  • 31
  • 1
  • 5
    #Name means that Excel cannot find that function. Have you stored the function in a regular module? It will not work if you put it into a Worksheet module – FunThomas Mar 23 '23 at 12:43
  • That code won't work - `Mid(txt, xstrt, 1)` always returns the first character. So taking "kayak" - first loop matches k with k, second loop doesn't match k with a. Without an even number of letters it will miss the middle letter - "kayak" is five letters. `xend / 2` is 2.5, so the loop runs twice and misses the third letter. Maybe `=TEXTJOIN("",FALSE,MID(A1,SEQUENCE(,LEN(A1),LEN(A1),-1),1))=A1` – Darren Bartrup-Cook Mar 23 '23 at 13:53
  • Saying that about the middle letter.... I guess there's only one middle letter in an odd number, so the middle will always equal the middle. :) – Darren Bartrup-Cook Mar 23 '23 at 13:55

1 Answers1

2

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
VBasic2008
  • 44,888
  • 5
  • 17
  • 28