VBA回文函数

问题描述 投票:0回答:1

我创建了以下函数来检查给定单词是否是回文并发回真或假。但是,该函数返回#NAME! .特此代码:

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

提前感谢您的帮助。

vba function palindrome
1个回答
1
投票

是回文(UDF)

  • 无需循环,当有
    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
  • 顺便说一句,使用正斜杠
    /
    来分隔,而不是
    xstrt
    使用
    i
    ,从字符串中删除空格(或不删除),并将所有字符转换为相同的大小写。
© www.soinside.com 2019 - 2024. All rights reserved.