MS Word

Close All Documents Except the Current One

The Problem:

I tend to end up with a stack of documents open and need to close all except the one I'm working on. Clicking the Close button gets tedious, even though it could hardly be easier.

The Solution:

You can easily create a macro (see Example 8-5) to close all the documents except the current one. To do so, you use a loop, a structure that tells VBA to repeat an action as long as a condition is true or until a condition is met.

Macro to closes all documents except the active document

Example 8-5
Sub Close_All_Except_Active_Document()
    Dim i As Integer
    Dim strKeepOpen As String
    strKeepOpen = ActiveDocument.Name
    For i = Documents.Count To 1 Step -1
      If Documents(i).Name <> strKeepOpen Then Documents(i).Close
    Next i
End Sub

As you can see, this macro is short and friendly: it even lacks comments about what the macro does (add them at the beginning if you like) and a message box to confirm that the user wants to take the action (you could add this too). Here's how it works:

  • The first group of lines declares an Integer variable named i and a String variable called strKeepOpen. The next line then assigns to strKeepOpen the name of the active document, which is the document the macro will leave open.

  • The For... Next loop uses the variable i as its counter and runs from Documents.Count (which returns the number of open documents) to 1, decrementing the counter by 1 (Step -1) at each iteration. (By default, loops increment the counter by one unless you specify otherwise. This loop needs to run backwards because each time the macro closes a document, the number of documents in the Documents collection decreases by one.) The If statement compares the name of the current document with strKeepOpen and closes the document if the name doesn't match. For example, if you have 12 documents open, Word starts with Documents(12) the twelfth document in the Documents collectionand closes that document if its name does not match the value of strKeepOpen. The Next i statement indicates the end of the loop, making execution return to the For statement. The loop continues to execute until the counter reaches 1.