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 calledstrKeepOpen
. The next line then assigns tostrKeepOpen
the name of the active document, which is the document the macro will leave open. -
The
For... Next
loop uses the variablei
as its counter and runs fromDocuments.Count
(which returns the number of open documents) to1
, 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 theDocuments
collection decreases by one.) TheIf
statement compares the name of the current document withstrKeepOpen
and closes the document if the name doesn't match. For example, if you have 12 documents open, Word starts withDocuments(12)
the twelfth document in theDocuments
collectionand closes that document if its name does not match the value ofstrKeepOpen
. TheNext i
statement indicates the end of the loop, making execution return to theFor
statement. The loop continues to execute until the counter reaches 1.