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.
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
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
iand a String variable called
strKeepOpen. The next line then assigns to
strKeepOpenthe name of the active document, which is the document the macro will leave open.
For... Nextloop uses the variable
ias 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
Documentscollection decreases by one.) The
Ifstatement compares the name of the current document with
strKeepOpenand 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
Documentscollectionand closes that document if its name does not match the value of
Next istatement indicates the end of the loop, making execution return to the
Forstatement. The loop continues to execute until the counter reaches 1.