Please Note: This article is written for users of the following Microsoft Word versions: 2007, 2010, 2013, and 2016. If you are using an earlier version (Word 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Word, click here: Checking for Matching Parentheses.

Checking for Matching Parentheses

Written by Allen Wyatt (last updated September 23, 2021)
This tip applies to Word 2007, 2010, 2013, and 2016


8

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:

If you would like to know how to use the macros described on this page (or on any other page on the WordTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

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.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Moving Breaks Quickly

Breaks in a document can be easily moved from one place to another using familiar editing techniques. The trick is to ...

Discover More

Adjusting Picture Appearance

Excel provides the Picture toolbar to help you modify any images in your worksheet. This tip explains how to use the ...

Discover More

Noting Formatting Inconsistencies

When you create a document, Word is constantly checking behind the scenes to make sure that what you type makes sense. ...

Discover More

Create Custom Apps with VBA! Discover how to extend the capabilities of Office 2013 (Word, Excel, PowerPoint, Outlook, and Access) with VBA programming, using it for writing macros, automating Office applications, and creating custom applications. Check out Mastering VBA for Office 2013 today!

More WordTips (ribbon)

Transposing Two Characters

If you have two characters in the wrong order, you might be interested in a shortcut you can use to switch their order. ...

Discover More

Finding Long Sentences

For certain types of writing, you may want to make sure that the sentences in your document do not exceed a certain ...

Discover More

Making the 'Welcome Back' Message Consistent and Permanent

When you open a document on which you previously worked, Word displays a "Welcome back" message that can help return you ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] (all 7 characters, in the sequence shown) in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is five more than 3?

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.


This Site

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.

Videos
Subscribe

FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.