Microsoft Word includes a standard macro AutoOpen that automatically runs when any document opens. With a reasonable novel naming system, we can create an AutoOpen macro to detect and layout our just opened novel document, so we can just get to work.
Thanks for your interest
This content is part of a paid plan.
Customizing a window layout using AutoOpen
Some macros apply differently to different document types, so it’s convenient to add a few extra steps and let the macro make some simple decisions for us. We’ll apply this concept to the standard Word macro AutoOpen to select different window layouts depending on the novel document type being opened.
For other macros, there is no sense creating different macros for different document types if each is doing only slightly different things, but we’ll focus on window layouts with the AutoOpen macro in this article.
Document types
In general work, a “document type” might mean a text file, spreadsheet, word processing document, or many more options. Here we’re usually working inside Microsoft Word, so everything is a Word document. Our job is writing and editing novels or other professional content; so by document type, we’re referring to “book”, “outline”, or “notes” documents.
Naming convention
When working on a novel, I tend to have three related document types. The main text of the book is stored in a separate file, and the document (file) name includes the word “book”. Sometimes I automatically (via another macro) create novel outlines based on chapter and scene headings, and I always include the word “outline” somewhere in the name. Finally, I usually have dedicated novel notes documents for each series or stand-alone novel where I include the word “notes” somewhere in the name.
Candidate problem: Novel documents window layout
When writing with a multimonitor setup, I had several window layout macros that would automatically resize and position my Word windows depending on which document type was opening. For my computer at the time, note and outline documents opened on the left or right monitor, and my novel text opened spanning most of the left two monitors.
At first, I created several Quick Launch bar buttons (or try it in Word for Mac) tied to the respective layout macros. The Quick Launch bar is the collection of buttons in the title bar to the left of the document name. Just click and resize the newly opened documents.
Easy and fast, right?
Yeah, but I eventually discovered the AutoOpen macro. I was basically putting the same documents in the same places every time, so why not let Word detect the document type and set up everything for me? And it only takes a little extra work.
AutoOpen macro for a window layout
AutoOpen is a standard Word macro that will run automatically every time an existing document is opened. It isn’t defined by default, but we can create one in the current document or in a template. A previous article talks about how to create a new macro from scratch. For simplicity, we’ll only consider one AutoOpen macro defined in the standard Word template Normal.dot which is where most macros are stored by default.
Given its special status, AutoOpen should be reserved for just that—steps to run on a document immediately when it is opened. It would be bad technique and maybe even asking for trouble to try to use it for any unrelated tasks.
Not running AutoOpen …
Technically, AutoOpen runs after the document is loaded, so the macro can act on it. If you don’t want the macro to run (or any other “auto” macro), hold the Shift key while opening the document.
Other Auto macros
Other similar standard “auto” macros in Word that you may find interesting include:
- AutoClose runs every time a document is closed.
- AutoNew runs when a new document is created.
- AutoExec runs when Word starts, or a global template is loaded but before any document is opened.
- AutoExit runs when the Word application is closed, or a global template is unloaded.
A few slight differences exist for these variations, but we’ll work only with AutoOpen which runs for existing documents not newly created ones.
AutoOpen macro skeleton
Create a macro called AutoOpen just like you would any other macro. I prefer to do it manually in the VBA editor (just press Alt+F11 or Option+F11 on a Mac), but you can also open the editor through the Macro ribbon commands. In Windows, use View → Macros → View Macros … and click the Create button. On a Mac use to menu option Tools → Macros → Visual Basic Editor. Create the following empty macro:
Word will recognize the name and use it as mentioned above.
It is a subroutine not a function, so no return value is allowed. Also, no parameters are needed—thus the open and close parentheses () after the macro name.
Macro steps
Our macro is not long today. We essentially need to detect our novel document type and run the respective layout macro covered in a previous article.
Get the document name
We’re detecting the document type based on one of several keywords included in the document name (not the file extension since most of our novel documents are Word documents).
Declaring text variable
It is convenient to store the document name in a plain text String variable which we’ll call sDocument.
I like to precede my plain text variables with an “s” to remind me they store a string value. VBA doesn’t care as long as I don’t use one of its reserved words like Selection.
Get document name
We get the active document title using the Name property of the ActiveDocument. The Name is literally a text string of the document title including the file extension. We then store it in the above text variable using an equals = sign.
The ActiveDocument refers to the currently opened document. Other documents or even multiple of them at the same time can exist inside the Word application, but we just need the active one. The ActiveDocument and its Name refer to the just opened document here because AutoOpen only runs after the document is loaded.
What is the Name?
This name stores the document title along with the file extension (defines the file type in Windows or Mac) but without any system drive or directory (folder location) information. For example, in my working document, sDocument holds the Name text something like:
Just for clarity, the variable does not store the left or right double quotes, just the text in between them.
Use lowercase text
Since we’re checking document names created by certain human authors, we can’t be sure about the case of any text in the title. It may save us some trouble later if we convert the entire name to a consistent case. VBA includes a standard function LCase(…) to convert the case of a String variable text to all lowercase.
LCase converts any alphabetic text stored in the String variable SomeText to all lowercase text, but it does not change any non-alphabetic or lowercase characters. It’s sibling function UCase(…) does the equivalent for uppercase text, but we only need one version.
LCase does not change the SomeText variable value directly, so if we need to use the result later, which is most of the time, we store it in another String variable. We can even use the same String variable if we’re sure we don’t need the original value anymore. The command for our example with the document name sDocument looks like:
If we want to cut out an extra step, we could just reference the ActiveDocument Name property here instead.
I prefer more concise commands overall, but it should always be clear. Any efficiency gains of uber concise code will never be noticed in a Word editing macro. If your head starts tilting or you start squinting as you read the steps, it’s probably not clear enough … or you need glasses. That could be a problem too when you’re an author.
Name comparison using Like searches
We’ll use a VBA string comparison operator Like to check whether a given word exists in the document name. Like is easy to use with a basic structure like:
An “operator” is just a fancy name for a symbol that takes two values and spits out a result (pardon the southern vernacular). For example, with the mathematical expression 2 + 3, the values are 2 and 3, and the operator is a plus + sign. The result is 5 which could be stored in a variable for later use.
Like is a search expression that takes two plain text strings and returns a True or False value to indicate whether a match was found.
Search text
More specifically, SomeText on the left side is usually a text variable to search. For our problem, SomeText is our document title which we stored in the variable sDocument.
Search pattern
After the Like operator, we include a search pattern SomePattern. We’re trying to find any of three possible keywords in the name text: book, outline, or notes. Search patterns can be stored in a String variable but may also just be stated explicitly in double quotes.
Like search result
Unfortunately, Like doesn’t give us any other information about the match other than a yes or no (as True or False) on an attempted match. For our current task, we need to check each word individually, so we know which document keyword was matched, if any. On the positive side, since Like gives us a True or False (Boolean) value as the result, we can easily use it in a conditional statement to make a decision in our macro.
Alternative searches with regular expressions (not used)
If you want more control over your search or more detailed information extracted from the text, look into regular expressions. It’s a powerful search tool available in many programming languages. Unfortunately, it has a rough learning curve but see this introductory article for using it in VBA.
Do the searches
When searching for a specific word such as “book”, the search pattern must allow for any characters on either side of the word. “Book.docx” is probably not a good document title if you plan to write more than one of them, but even there, we need to allow for the ".docx" on the right of the text. We allow any number of additional characters in the match using a “wildcard” asterisk character * (literally borrowing the term from wild cards in card games), so the search pattern becomes “*book*”. Fortunately, an asterisk also allows for no characters in the same position of the pattern, so we lose nothing by including it.
We use the document name variable and the search pattern with the Like operator to check for a match.
We previously changed the name text to all lowercase, so we do not need any other search pattern variations such as “*Book*”. More generally, we could use something like “*[Bb]ook*” to catch both capitalizations of the word using a character set in square brackets (just hinting that more options are available depending on how you wish to implement it).
Other relevant searches
For outline or notes documents, we simply change the matched word.
Of course, include other variations as needed or change the keywords based on your own naming conventions.
Window layout macros
We previously defined a window layout macro in a separate article which can be modified to layout your own documents as desired. I have three main versions for my novel related documents.
None take a parameter, and all do what the name implies, so we just run the respective macro when we need to layout the document window.
Conditional statement
Now we need to decide the document type and run the respective layout macro, but we do nothing for any other document. The rough conditional statement reads something like:
VBA often reads like English anyhow, but this is called “pseudocode” which is usually some mishmash of real commands with some descriptive wording. It just helps us organize our thoughts before we create the actual VBA steps.
The VBA terms for “else if” part is literally a VBA keyword ElseIf … Then with a True or False (Boolean) condition in between. Since we’re not laying out other document types, we’ll omit the Else part. Our three keyword matches were given above, so we include them now. In VBA, the conditional statement becomes:
Of course, we could add additional cases as desired by just chaining together more ElseIf statements.
We do not need to "Call" the layout macros since they do not require any arguments, but it would not hurt anything to use it.
Gotchas
Where could we encounter problems?
Novel naming convention?
Of course, the above document name matches require us to implement and be consistent with a naming system for any novel-related documents. I’m generally not a fan of macros that require a user to do things a certain way, but using consistent file names seems more like good, basic organization of my novel-related files.
Ignored commands?
Some commands seem to be ignored within the AutoOpen macro. I am only speaking from experience rather than as a Word VBA insider or tech wizard. For example, I had a command to restore normal window state when working in Windows since some of the layout commands cause an error if the Word window is maximized. The command in question was:
Without going into a lot of detail, the intention was to remove a possible maximized window state before giving any window layout commands. Unfortunately, Word would not invoke the above command (early enough?) within the AutoOpen macro, so when my book document finally opened, the macro would still crash on certain position or size settings.
I cannot predict all commands that will encounter problems, so this is more of a warning to not expect everything to work exactly like we want or imagine when using AutoOpen. Test your macros, or they’ll test your patience.
Final automatic layout macro
As a reminder, AutoOpen is a special macro that Word recognizes and runs automatically when any document opens (unless we’re holding the Shift key). Assembling the macro with the fleshed out conditional statement to detect the document type, we have:
While this macro doesn’t save loads of time, it makes the process of getting started writing or editing smoother which feels great when I want to get into the flow quickly. Removing any extra friction when getting started helps me get to the fun stuff faster.
I went a step further for my personal version and included layout differences between my Mac or Windows setups (see article on detecting Word for Mac in VBA).
Alternative functions for document detection
The above searches using Like are relatively easy to read, but I also include document type detections in other macros. As a result, it’s more convenient to define a nearly trivial function in case I ever want to change my novel naming conventions. We basically need a quick function to return a True or False value based on whether the active document is a book.
Document detection function skeleton
Our function skeleton is:
The function requires no parameters since we’re focused on the active document. Similar to the Like search result, the return value is a True or False (Boolean) value for whether the keyword “book” is detected within the document name, so we use “As Boolean”.
Return value
We immediately store the Like search result as a True or False value in the function name. This is the returned value of the function.
With this search, we refer to the ActiveDocument.Name property directly rather temporality storing it in an sDocument variable just to keep the function super brief. The name text isn't needed anywhere else in this function.
Detect book document function
Padding this inside the nearly trivial function, we have:
Done.
It’s a super simple function, and it seems redundant redundant at first, but it makes our other macros a tiny bit easier to implement when we need to detect a book document type. I just use the IsActiveDocumentBook function wherever I need to detect a book document type. The Like operator is clear in its own way, but I also like the way this function name reads even more like English.
If I make any changes later, I don’t need to search through my macros for all occurrences of novel document types.
Outline and notes document functions
Similar functions apply to other Like match conditions for outline or note documents. The corresponding functions are:
Revised AutoOpen macro with document type functions
If you like these modified detection functions, the slightly revised AutoOpen macro is:
Not a big difference, and it’s not essential, but it’s cleaner and allows easier modifications to the document type keywords if desired.