Thursday, February 10, 2005
Excel Function to check if text is palindrome or not
Definition of palindrome as given in Answers.com
pal·in·drome (păl'ĭn-drōm')
n.
A word, phrase, verse, or sentence that reads the same backward or forward. For example: A man, a plan, a canal, Panama!
I've written this function in Excel 2003- VBA and it'll return the values True or False depending on the result. The function is not case sensitive, it can take numbers as input, the text can have spaces and characters like, [, ? . ] . You can add more if you want, it's just an or statement. There's minimal error handling though.
Function IsPalindrome(ByVal inputtext As String) As Boolean
Dim i As Long, length As Long
Dim tmp2 As String, tmp3 As String
On Error GoTo exitsub
length = Len(inputtext)
If length = 0 Then
MsgBox "Enter some value, exiting sub now", vbCritical, "Empty cell"
GoTo exitsub
End If
inputtext = LCase(inputtext)
tmp2 = ""
tmp3 = ""
'removing spaces and other chars
For i = 1 To length
tmp2 = Mid(inputtext, i, 1)
If tmp2 = " " Or tmp2 = "," Or tmp2 = "?" Or tmp2 = "." Then GoTo continue1
tmp3 = tmp3 & tmp2
continue1:
Next i
inputtext = tmp3
'reversing the word and checking
If inputtext = StrReverse(inputtext) Then
IsPalindrome = True
Else: IsPalindrome = False
End If
exitsub:
End Function
pal·in·drome (păl'ĭn-drōm')
n.
A word, phrase, verse, or sentence that reads the same backward or forward. For example: A man, a plan, a canal, Panama!
I've written this function in Excel 2003- VBA and it'll return the values True or False depending on the result. The function is not case sensitive, it can take numbers as input, the text can have spaces and characters like, [, ? . ] . You can add more if you want, it's just an or statement. There's minimal error handling though.
Function IsPalindrome(ByVal inputtext As String) As Boolean
Dim i As Long, length As Long
Dim tmp2 As String, tmp3 As String
On Error GoTo exitsub
length = Len(inputtext)
If length = 0 Then
MsgBox "Enter some value, exiting sub now", vbCritical, "Empty cell"
GoTo exitsub
End If
inputtext = LCase(inputtext)
tmp2 = ""
tmp3 = ""
'removing spaces and other chars
For i = 1 To length
tmp2 = Mid(inputtext, i, 1)
If tmp2 = " " Or tmp2 = "," Or tmp2 = "?" Or tmp2 = "." Then GoTo continue1
tmp3 = tmp3 & tmp2
continue1:
Next i
inputtext = tmp3
'reversing the word and checking
If inputtext = StrReverse(inputtext) Then
IsPalindrome = True
Else: IsPalindrome = False
End If
exitsub:
End Function
Labels: String Operations