Welcome toWord.Tips.Net
Ask a Word Question
Make a Comment
Learn Access Now
Free Printable Forms
Beauty Tips
Car Tips
Cleaning Tips
College Tips
Cooking Tips
Excel2007 Tips
ExcelTips
Family Tips
Gardening Tips
Health Tips
Home Tips
Legal Tips
Money Tips
Organizing Tips
Pest Tips
Pet Tips
Wedding Tips
Word2007 Tips
WordTips
Collapsing and Expanding Subdocuments
Unless you are writing very short documents, cleaning up can be one of the hardest parts of writing. The following macro double-checks your document, paragraph by paragraph, to determine if you have a balanced number of parentheses. The macro counts the number of left parentheses in each paragraph of your document and makes sure you have the same number of right parentheses. If you don't, the macro inserts a paragraph before the unbalanced paragraph indicating the error.
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
NumPara = ActiveDocument.Paragraphs.Count
ReDim CheckP(NumPara)
MsgText = "***Unbalanced parens in the next paragraph"
For J = 1 To NumPara
CheckP(J) = False
WorkPara = ActiveDocument.Paragraphs(J).Range.Text
If Len(WorkPara) <> 0 Then
LeftParens = CountChars(WorkPara, "(")
RightParens = CountChars(WorkPara, ")")
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
Note that there are actually two macros here. The CountChars function is called from within the main CheckParens macro. It is this latter macro (CheckParens) that is the one you should actually invoke on your document. When the macro is finished, you can search through the document, looking for the wording "***Unbalanced parens" to see where you may have problems.
Tip #1308 applies to Microsoft Word versions: 97 2000 2002 2003 2007
Great Idea! Word is a tool to get what you really want—printed output. This means you need to make sure that Word works as well as possible with your printer, whether it is sitting on your desk or in a room down the hall.