除非您编写的文档很短,否则清理可能是最难的部分之一。下面的宏逐段仔细检查您的文档,以确定圆括号的数量是否平衡。宏会计算文档各段中左括号的数量,并确保右括号的数量相同。如果您不这样做,宏将在不平衡段落之前插入一个段落,指示错误。

Sub CheckParens()

Dim WorkPara As String     Dim CheckP() As Boolean     Dim NumPara As Integer, J As Integer     Dim LeftParens As Integer, RightParens As Integer     Dim MsgText As String     Dim OpenChar As String     Dim CloseChar As String

OpenChar = "("

CloseChar = ")"

MsgText = "Unbalanced parens in the next paragraph"



NumPara = ActiveDocument.Paragraphs.Count     ReDim CheckP(NumPara)



For J = 1 To NumPara         CheckP(J) = False         WorkPara = ActiveDocument.Paragraphs(J).Range.Text         If Len(WorkPara) <> 0 Then             LeftParens = CountChars(WorkPara, OpenChar)

RightParens = CountChars(WorkPara, CloseChar)

If LeftParens <> RightParens Then CheckP(J) = True         End If     Next J

For J = NumPara To 1 Step -1         If CheckP(J) Then             Selection.HomeKey Unit:=wdStory, Extend:=wdMove             If J > 1 Then                 Selection.MoveDown Unit:=wdParagraph, _                   Count:=(J - 1), Extend:=wdMove             End If             Selection.InsertParagraphBefore             Selection.MoveLeft Unit:=wdCharacter, Count:=1             Selection.Style = "Normal"

Selection.TypeText Text:=MsgText         End If     Next J End Sub

Private Function CountChars(A As String, C As String) As Integer     Dim Count As Integer     Dim Found As Integer

Count = 0     Found = InStr(A, C)

While Found <> 0         Count = Count + 1         Found = InStr(Found + 1, A, C)

Wend     CountChars = Count End Function

请注意,这里实际上有两个宏。从主要CheckParens宏中调用CountChars函数。您应该在文档上实际调用的是后者(CheckParens)宏。宏完成后,您可以搜索文档,查找“不平衡的括号”,以查看可能存在问题的地方。

同样,请注意,编写此宏的方式很容易修改,以搜索其他“成对”字符。您需要做的就是更改分配给OpenChar,CloseChar和MsgText变量的内容。例如,如果您要检查不匹配的括号,则可以通过以下方式更改这些变量:

OpenChar = "["

CloseChar = "]"

MsgText = "Unbalanced brackets in the next paragraph"

注意:

如果您想知道如何使用此页面(或_WordTips_网站上的任何其他页面)中描述的宏,我准备了一个包含有用信息的特殊页面。

_WordTips_是您进行经济有效的Microsoft Word培训的来源。

(Microsoft Word是世界上最流行的文字处理软件。)本技巧(1018)适用于Microsoft Word 2007、2010、2013和2016。您可以在此处找到适用于Word较旧菜单界面的本技巧的版本: