Using Visual Basic for Applications with Micorosft Word

VBA is a simplified programming language that uses Visual Basic syntax to help users extend the functionality of Microsoft Office programs. I have experience doing excellent things with VBA and Excel. This page gives some tips and some links on using VBA with Word to create forms and automate tasks.

Enabling macros
The code we write resides in macros. In order to use VBA with word, we need to set the proper security settings. Under Tools - Macro - Security, set the security level to Medium. The next time you open a document with macro's, Word will ask you about allowing them to run. When that happens, choose "Enable Macros" for documents you trust.

Running code whenever word starts
To create a program that starts automatically with Word, follow the following steps:

  1. Start Word
  2. Go to Tools - Options - File Locations
  3. Find the "Startup" file type and write down the folder it points to.
  4. Go to Tools - Macro - Visual Basic Editor
  5. In the editor, go to Insert - Module
  6. Enter the following code:
  7. Public Sub AutoExec()
      MsgBox ("Hello World!")
    End Sub
    
  8. Use SaveAs to save the document as a document template type in the folder you wrote down on step 2.

All done! You can now try closing and re-opening word and voila! The message Hello World appears. You can replace this with your own code. To prevent this message from appearing in the future, simply delete the file you just created.

Running code when a document is opened
To create code that runs whenever you open a particular document, you need to create a Document_Open() subroutine for that object:

  1. Go to Tools - Macro - Visual Basic Editor
  2. In the Project Browser, double-click the Word document object to edit the object code.
  3. Add the following code:
  4. Private Sub Document_Open()
      MsgBox ("Document Opened!")
    End Sub
     
  5. Close the Document Window (both Visual Basic and Word) and open it again.
Done! Your code should now run, presenting the message box in this example. If it doesn't run, make sure you enabled Macros in the security settings as explained earlier under "Enabling macros".

Recommended Links:

  • VBA - The Word Working Parner
  • Word-VBA Code Samples
  • Word-VBA Code Samples Printable Version (All rights reserved to the original author)

  • Using VBA with Word tutorial - Gilad Israeli, June 2005.
    For more help, write me.