Written by Allen Wyatt (last updated September 23, 2021)
This tip applies to Word 2007, 2010, 2013, and 2016
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 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
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.
Note, as well, that the way this macro is written, you could easily modify it to search for other "paired" characters. All you would need to do is change what is assigned to the OpenChar, CloseChar, and MsgText variables. For instance, if you wanted to check for unmatched brackets, you could change those variables in this way:
OpenChar = "[" CloseChar = "]" MsgText = "***Unbalanced brackets in the next paragraph"
Note:
WordTips is your source for cost-effective Microsoft Word training. (Microsoft Word is the most popular word processing software in the world.) This tip (1018) applies to Microsoft Word 2007, 2010, 2013, and 2016. You can find a version of this tip for the older menu interface of Word here: Checking for Matching Parentheses.
Comprehensive VBA Guide Visual Basic for Applications (VBA) is the language used for writing macros in all Office programs. This complete guide shows both professionals and novices how to master VBA in order to customize the entire Office suite for their needs. Check out Mastering VBA for Office 2010 today!
Section marks are used regularly in the writings of some industries, such as in legal documents. If you need a way to ...
Discover MoreWord provides access to a wide variety of characters either from the keyboard or from the Symbol dialog box. Up and above ...
Discover MoreNeed to move a few paragraphs around in your document? Word provides a couple of handy shortcuts that make it very easy ...
Discover MoreFREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."
2022-01-12 05:47:09
Ken Endacott
The macro CheckParens flags all apparent unbalanced parenthesis in the document after which it is necessary to go through the document to correct each unbalance (or ignore) and remove the flag statement.
A better way would be to pause at each unbalance and provide options to ignore or correct at the time then continue on to the next unbalance. This can be achieved in a macro with a simple non modal user form that contains option buttons.
Step1. In the VBA editor click the Insert tab and select UserForm to display UserForm1.
Step 2. Using the toolbox place two command buttons on the form , these will have the default names CommandButton1 and CommandButton2. Click inside the buttons and change their labels to “Next” and “Cancel”. Drag the borders of the userform to give a compact form.
(see Figure 1 below)
Step 3. If Project Explorer is not visible click View > Project Explorer. Right click UserForm1 (expand Forms if it is not visible) and select View Code. In the UserForm1 code window insert:
Private Sub CommandButton1_Click()
NextAction(1)
End Sub
Private Sub CommandButton2_Click()
Selection.Collapse
Userform1.hide
End Sub
Step 4. Insert > Module. In the Module1 code window insert:
Sub InitialiseForm()
Selection.HomeKey Unit:=wdStory
Userform1 .Show(False)
NextParenthesis
End Sub
Sub NextAction(Dum As Long)
Dim aRange As Range
Selection.Paragraphs(1).Range.Select
Selection.MoveRight Unit:=wdCharacter, Count:=1
NextParenthesis
End Sub
Private Sub NextParenthesis()
Dim WorkPara As String
Dim aPara As Paragraph
Dim aRange As Range
Dim j As Long
Dim k As Long
Set aRange = ActiveDocument.Range(Start:=Selection.Start, End:=ActiveDocument.Range.End)
For Each aPara In aRange.Paragraphs
WorkPara = aPara.Range.Text
k = 0
For j = 1 To Len(WorkPara)
If Mid(WorkPara, j, 1) = "(" Then k = k + 1
If Mid(WorkPara, j, 1) = ")" Then k = k - 1
If k < 0 Then
aPara.Range.Select
Exit Sub
End If
Next j
If k <> 0 Then
aPara.Range.Select
Exit Sub
End If
Next aPara
Userform1.hide
Selection.EndKey Unit:=wdStory
End Sub
Step 5. Run the macro InitialiseForm. The first paragraph with unmatched parentheses will be highlighted and the userform displayed. The paragraph can be corrected manually while the userform remains on the screen. Clicking the Next button will advance to the next paragraph that has unbalanced parentheses.
Figure 1.
2022-01-11 13:48:10
Tomek
Andrew,
In my comment i mentioned that the list would be manually numbered. Many people still do not use automatic numbering, even though it is generally a better practice.
What I wanted to alert users to, was that there may be situations when parentheses may be unbalanced but it would be OK.
Worse, if in the paragraph manually numbered say 3) there was an open parenthesis without a matching closed parenthesis such paragraph would not be marked as unbalanced.
2022-01-10 10:21:37
Andrew
Tomek, No and Yes.
No, in that a range's text does not include the text of the automatic numbering. (Would that it did! Wouldn't it be nice to search for an automatic number?)
Yes, in that a range's text search does include the text of the field *reference* to an automatic number.
For example in the text "9) See paragraph 4) above."), the parenthesis in the "4)" reference would show as unbalanced, but the parenthesis added in the automatically numbered "9)" itself would not.
Andy.
2022-01-09 12:31:49
Tomek
Just a thought:
What if you have a manually numbered list, in which the numbers are like 1), 2) 3), etc? This will cause unbalanced parentheses, wouldn't it.
2022-01-08 08:38:45
shhada bsher
Thank You :)
2021-12-16 13:49:59
lady
this macro runs an endless loop. how do i get it to stop at the end of the document?
2017-05-02 12:39:26
dave
Brilliant. For amateurs like myself, seeing little programming examples like this helps give my confidence to "take the lid off" VBA and see how I can approach things. Thanks Allen.
2017-05-01 14:15:37
Phil Reinemann
I haven't see an array of binary values used in VBS before so that was a enlightening answer!
The count-down of number of paragraphs was pretty neat too.
Just a couple of things I wouldn't have thought of until I saw this.
Got a version of Word that uses the ribbon interface (Word 2007 or later)? This site is for you! If you use an earlier version of Word, visit our WordTips site focusing on the menu interface.
Visit the WordTips channel on YouTube
FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."
Copyright © 2023 Sharon Parq Associates, Inc.
Comments