拼写检查Excel函数中的单个单词

Whi*_*uit 10 excel vba spell-checking

这个小的Excel VBA函数总是返回false,没有传入任何单词.

Function SpellCheck(SomeWord As String)

SpellCheck = Application.CheckSpelling(SomeWord)

End Function
Run Code Online (Sandbox Code Playgroud)

实际上,在IDE中,我可以验证Application.CheckSpelling("hello")是否失败,尽管Excel拼写检查程序确实检测到了拼写错误.

我要做的是,如果拼写正确,每个单词都会得到一个T/F值.

Sid*_*out 12

就像我在评论中提到的那样有效.

Option Explicit

Sub Sample()
    MsgBox SpellCheck("hello") '<~~ Returns True
    MsgBox SpellCheck("daasd") '<~~ Returns False
End Sub

Function SpellCheck(SomeWord As String) As Boolean
    SpellCheck = Application.CheckSpelling(SomeWord)
End Function
Run Code Online (Sandbox Code Playgroud)

Application.CheckSpelling不会纠正或提供纠正拼写错误的单词,它只会返回TrueFalse

我测试过了

?Application.CheckSpelling("hello")

在即时窗口中,它返回 True

编辑:Application.CheckSpelling从UDF 调用将始终返回False.上次我检查时,它仍然是一个错误,没有办法解决它.如果有最近的更新,那么我不知道它.:)

更多编辑

这是你的功能略有修改,它也可以作为UDF :)

从这个链接中得到了想法

Function SpellCheck(rng As Range) As Boolean
    Dim oxlAp As Object
    Set oxlAp = CreateObject("Excel.Application")
    SpellCheck = oxlAp.CheckSpelling(rng.Value)
    oxlAp.Quit
    Set oxlAp = Nothing
End Function
Run Code Online (Sandbox Code Playgroud)


End*_*oth 5

需要注意的一个缺陷是Application.CheckSpelling将为任何具有您执行拼写检查的语言代码页之外的字符的文本返回True.

例如,用英语检查nő会返回True.显然Excel还没有(截至2010年)完全进入Unicode世界.

如果你的应用程序出现问题,你必须事先用代码页之外的字符筛选文本,或者你可以借用Word的拼写检查功能,它没有这个bug,例如像这样(改编自www.vb-tec) .de):

    Public Function CheckSpellingWd( _
            ByRef Text As String, _
            Optional ByVal IgnoreUpperCase As Boolean = False, _
            Optional ByVal ReUse As Boolean = True _
        ) As Boolean

        'Reuse Word object on next call
        Static wd As Word.Application

        If Len(Text) > 0 Then
            'create Word object on first call
            If wd Is Nothing Then
            Set wd = New Word.Application
            wd.DisplayAlerts = wdAlertsNone
            End If

            'Do spellcheck
            CheckSpellingWd = wd.CheckSpelling(Text, , IgnoreUpperCase)
        Else
            'Return True on empty string
            CheckSpellingWd = True
        End If
    End Function
Run Code Online (Sandbox Code Playgroud)

现在可以很好地检查Unicode,理论上,您可以提供字典文件路径作为CheckSpelling函数的参数,以检查您拥有字典文件的任何语言:

Application.CheckSpelling(Word, CustomDictionary, IgnoreUppercase, MainDictionary, _
    CustomDictionary2, CustomDictionary3, CustomDictionary4, CustomDictionary5, _
    CustomDictionary6, CustomDictionary7, CustomDictionary8, CustomDictionary9, _
    CustomDictionary10)
Run Code Online (Sandbox Code Playgroud)

实际上,无论您指定哪个字典(在Word 2010中检查,不确定以前的版本),都使用默认语言的主词典(在文件/选项/语言中设置)完成检查.您只能手动更改该设置(并且必须重新启动Word才能使更改生效).

默认语言设置由注册表项控制.在Office 2010中:

HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Common\LanguageResources\InstallLanguage
Run Code Online (Sandbox Code Playgroud)

所以从理论上讲,你可以自动化语言更改,使用VBA包装器到Windows Scripting,WMIWinAPI来更改注册表(然后重新启动Word),但在启用了UAC的Windows 7上,我遇到了权限问题,这就是我放弃了实验.我只尝试过WinAPI路线.