How to Program MS Word with VBA – An Introduction
Underneath MS Word’s unassuming document interface there is a very powerful code engine — VBA (Visual Basic for Applications). You can use VBA to program Word all kinds of things that are not possible to achieve by just using Word’s built-in menu functions.
How to display VBA Editing Environment
1) Open your MS Word document of choice.
2) Press Alt + F11 (on a Windows PC) to launch the VBA Editor and its most important Project Pane on the upper-left corner of the VBA window:
Every open MS Word document is represented in VBA as a Project.
In the above example, since there are two documents open in Word, they are represented by two Projects.
One of them does not have a name yet (the first one). Thus it is represented by the generic label
- Project(Document)
where “Document” is the name with which the document will be saved.
The second project displays the name with which the second document was saved: ”
How to convert and synch files from Dropbox or Google Drive”
There is a second type of VBA project:
- TemplateProject(Document)
displayed only if we are working with a template document.
SUMMARY: There are two types of VBA projects: the (regular) Project, and TemplateProject.
What does a VBA project contain?
A VBA project may have some or all of the following sub-elements (in the tree-view diagram):
- Document Objects
- UserForm Objects
- Standard Modules
- Class Modules
- References
We will explain all these in other blog posts.
Both projects (above) happen to contain only one object called “This Document.” That is the document which is currently open in MS Word. If you close a document, that project will disappear from VBA’s Project pane.
Types of Object Components
Both the Document Objects and UserForm Objects are made up of the following components:
- Code Component – hidden from the user until she fires up the VBA editor
- User Interface – also known regularly as the “Word document” that a reader views and reads
Types of Modules
Word VBA has two types of modules:
- Standard Modules – a code module that contains regular functions and subroutines (like a macro)
- Class Modules – a code module created for Custom Objects (an advanced topic requiring heavy-duty coding skills)
Types of Module Components
A module, on the other hand, has a single component:
- Code Component – hidden from the user until she fires up the VBA editor
Types of Code Components
A code is written by including any combination of the following events:
- Open Event – anything that happens when an existing Word document is opened
- Close Event – anything that happens when an open Word document or Template is closed
- New Event – anything that happens to a Word Template when a new Word document based on that template is created