Word句子长度检查VBA代码问题:含逗号时误判短句
问题根源
Word自带的Words.Count统计逻辑有坑——它会把逗号、句号这类标点符号,甚至分隔标点的空格都算作"单词",这就导致带标点的短句子被误判成长句标红,完全不符合你的预期。
修复后的完整代码
Sub AutoExec() ' The AutoExec is a special name meaning that the code will run automatically when Word starts CustomizationContext = NormalTemplate ' Create key binding to change the function of the spacebar so that it calls the macro Check_Sentence ' each time the spacebar is pressed KeyBindings.Add KeyCode:=BuildKeyCode(wdKeySpacebar), _ KeyCategory:=wdKeyCategoryMacro, _ Command:="Check_Sentence" ' It will be useful to be able to turn the checking on and off manually ' so allocate ctrl-shift-spacebar to turn the checking off KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyControl, wdKeyShift, wdKeySpacebar), _ KeyCategory:=wdKeyCategoryMacro, _ Command:="SetSpaceBarOff" ' and allocate ctrl-spacebar to turn the checking back on KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyControl, wdKeySpacebar), _ KeyCategory:=wdKeyCategoryMacro, _ Command:="SetSpaceBarOn" End Sub Sub SetSpaceBarOn() KeyBindings.Add KeyCode:=BuildKeyCode(wdKeySpacebar), _ KeyCategory:=wdKeyCategoryMacro, _ Command:="Check_Sentence" MsgBox ("sentence length checking turned on") End Sub Sub SetSpaceBarOff() With FindKey(BuildKeyCode(wdKeySpacebar)) .Disable End With MsgBox ("sentence length checking turned off") End Sub Sub Check_Sentence() Dim long_sentence As Integer Dim realWordCount As Integer ' pressing the spacebar calls this macro so have to assume the user wanted a space to appear ' in the text. Therefore put a space character into the document Selection.TypeText (" ") 'Set number of words to be a long sentence long_sentence = 25 For Each Test_Sentence In ActiveDocument.Sentences ' 调用自定义函数统计有效单词数 realWordCount = GetRealWordCount(Test_Sentence) If realWordCount > long_sentence Then ' if it longer than our limit Test_Sentence.Font.Color = wdColorRed ' Test_Sentence.Font.Underline = wdUnderlineDotted ' show long sentences with a dotted underline Else Test_Sentence.Font.Color = wdColorBlack ' Test_Sentence.Font.Underline = wdUnderlineNone ' turn of the underline End If Next ' next sentence End Sub ' 自定义函数:统计句子中的有效单词数(排除标点和空白) Function GetRealWordCount(sentence As Range) As Integer Dim word As Range Dim count As Integer count = 0 For Each word In sentence.Words ' 去除单词前后的空白字符 Dim cleanWord As String cleanWord = Trim(word.Text) ' 判断是否为有效单词:长度大于0,且不是纯标点(包含至少一个字母/数字) If Len(cleanWord) > 0 And (cleanWord Like "*[A-Za-z0-9]*") Then count = count + 1 End If Next word GetRealWordCount = count End Function
关键改动说明
- 新增
GetRealWordCount函数:这个函数会遍历句子里的每个"Word",先去掉前后空白,再判断是否包含至少一个字母或数字——只有符合这个条件的才会被算作有效单词,彻底排除了标点符号的干扰。 - 修改
Check_Sentence的判断逻辑:不再直接用Test_Sentence.Words.Count,而是调用自定义函数得到真实的单词数,再和阈值25对比,避免误判。 - 保留原有功能:自动启动、快捷键开关这些功能完全不变,不影响你的使用习惯。
你可以测试一下带逗号的句子,比如"Hello, this is a short sentence with some commas, but it should not be marked red.",现在它会被正确统计为有效单词数,不会因为逗号被误标红了。
内容的提问来源于stack exchange,提问作者Oded
相关产品推荐
相关产品推荐

