Insights

Categories

Word and Visual Basic for Applications (VBA): Worth the Effort? (Part 2)

Nov 20, 2015

In the first post in this series, we described VBA for Word and how it could be useful to writers. In this part, we delve into VBA and explore some basic tasks:

  • Getting started
  • Writing text to a document
  • Reading text from a document
  • Looping through all the paragraphs in a document

Getting Started

There are three things you need to do to start using VBA:

  • Open the VBA Editor – Create a blank document in Word and press Alt+F11. The Microsoft Visual Basic for Applications window (the VBA Editor) opens. It may seem intimidating at first, but don’t be discouraged — it is much easier than you think!
  • Create a Placeholder (Module) for Your Code – In the VBA Editor, on the left, you see two top-level folders called Normal and Project (Document1). Normal is the template that most Word documents are based on by default; you can ignore it in this context. Project (Document1) is the blank document that you just created. This is where you add your code.To do that, you must create a placeholder into which you can put your code. This placeholder is known as a Module. Right-click Project (Document1) and choose Insert Module. A new Module1 (Code) window opens. You’re ready to add some code.
  • Create a Subroutine – In Word VBA, the simplest way to perform a task is to use a subroutine. Create a subroutine by typing Sub <Name>, where <Name> can be anything other than the few reserved keywords that VBA uses. Typically, you choose a name that closely relates to the task you want to perform as demonstrated in the following examples.

Writing Text to a Document

Writing text is a fundamental task you will need in almost any macro. For example, let’s say you want to get text from a different source (another Word document, an Excel document, or even a web page). Once you acquire the text, you will need to write it into your document. This section demonstrates one easy method you can use to write text.

Let’s create a subroutine called WriteText.

Note that when you type Sub WriteText and press Return, the VBA editor automatically adds an End Sub statement, which is the statement required to close the subroutine. This auto-complete feature is very helpful (as you will discover).

On the blank line between the Sub WriteText() and the End Sub statements, press Tab, then type:
Selection.InsertAfter ("Hello World!")

So your complete code looks like this:

Sub WriteText() 
    Selection.InsertAfter ("Hello World!")
End Sub

Note that once you’ve typed Selection., the editor displays a drop-down list with possible alternatives. This is a feature that Microsoft calls IntelliSense. It helps you avoid spelling and syntax errors.

Now, with the cursor inside the subroutine, click (Run Sub/UserForm) on the toolbar. Alternatively, from the menu, choose Run > Run Sub/User Form.

Result: The script writes the text ‘Hello World!’ into Document1.

Congratulations! You have just created and run your first Word VBA macro. I think you’ll agree that it’s not too difficult.

A few things to note:

  • Selection is a VBA object that represents whatever is selected at the time it is used. If nothing is selected, it represents the position of the cursor.
  • InsertAfter is a method of the Selection object that inserts whatever text you specify after the selection.
  • The method’s parameter (in parentheses) is the actual text that will be inserted. The double quotes tell VBA that you want to insert the string of text between them.

OK, so now you know how to write text into a Word document at the position of the cursor. Let’s save the document before we proceed.

In the VBA editor, choose File > Save As, and in the Save As dialog, select Word Macro-Enabled Document as the file type. This is a special format for documents that contain macros. Use ‘Hello World’ as the file name and press the Save button.

Reading Text from a Document

Reading text is a another fundamental task you will need in many macros. For example, you may want to read the text in the third paragraph of multiple documents for some specific reason. This section demonstrates a simple way to read text.

Continuing with your Hello World document, add the following lines of text so that you have something to read:

Apples
Oranges
Mary had a little lamb.

Now you have four paragraphs in your document. Let’s create a small VBA macro to read the third paragraph. In the VBA window, type the following text after your WriteText() subroutine:

Sub ReadText()
    MsgBox (ActiveDocument.Paragraphs(3).Range.Text)
End Sub 

With the cursor inside the subroutine, click  (Run Sub/UserForm) on the toolbar.

Result: A dialog box containing the word ‘Oranges’ pops up. This is the text in paragraph 3.

That’s it! You have programmatically read some text from the Word document. Using this macro, you can read the third paragraph of any Word file. Once again, surprisingly easy!

A few things to note:

  • MsgBox() is an easy way to display the values of items. It is really useful for debugging. In this example, you use it to show the text content of paragraph 3.
  • ActiveDocument is the currently active document, in this case the Hello World document you saved.
  • Paragraphs is a collection (or group) of all the paragraphs in the active document. You want the third element in that collection, so you can write the notation Paragraphs(3).
  • Range.Text represents the text of the paragraph.

The text of the paragraph is not the only thing you can read. For example, you can read the style of the paragraph. Add a second line (highlighted) to your macro as shown:

Sub ReadText()
    MsgBox (ActiveDocument.Paragraphs(3).Range.Text)
    MsgBox (ActiveDocument.Paragraphs(3).Style) 
End Sub

With the cursor inside the subroutine, click  (Run Sub/UserForm) on the toolbar.

Result: The dialog box pops up twice. The first time, it contains ‘Oranges’ as before. The second time, it contains ‘Normal’, which is the name of the style associated with the paragraph.

Looping Through All the Paragraphs in a Document

Another task that is often necessary is to loop through all the paragraphs in a document. For example, you may want to look at each paragraph for some style or characteristic. In VBA, it is easy to loop through the paragraphs in a document.

Type the following code in the VBA editor window:

Sub LoopThroughParas()
    For Each para In ActiveDocument.Paragraphs
        MsgBox (para.Range.Text)
    Next para
End Sub

With the cursor inside the subroutine, click  (Run Sub/UserForm) on the toolbar.

Result: The dialog box pops up four times with the content of each paragraph.

A few things to note:

  • For ... Next is the VBA statement combination that does the looping.
  • ActiveDocument.Paragraphs is the collection of all the paragraphs in the active document.
  • para is a variable that represents one paragraph.
  • para.Range.Text is the content of the paragraph. This changes on each loop, as a different paragraph is examined each time.
  • MsgBox pops up the dialog box each time through the loop.

So with five short lines of code we can loop through every paragraph in the document, including paragraphs in tables. This works regardless of the size of the document. You could apply this macro to a document that is several hundred pages long. However, that would not be wise, because a dialog box would pop up for each and every paragraph. That would be a lot of dialog boxes to respond to.

Fortunately, there is another way to display output. Instead of using the MsgBox line, you can use Debug.Print <something>. The result is displayed in the Immediate window (if it’s not already visible in the VBA editor, choose View > Immediate window).

Replace the MsgBox line with Debug.Print para.Range.Text in your code as highlighted in the following code snippet:

Sub LoopThroughParas()
    For Each para In ActiveDocument.Paragraphs
        Debug.Print para.Range.Text 
    Next para
End Sub

With the cursor inside the subroutine, click  (Run Sub/UserForm) on the toolbar.

Result: The content of each paragraph is now written to the Immediate window.

Have you encountered situations where you needed to check through a document paragraph by paragraph for some reason? Do you think VBA could have helped? Let us know.

In the next post, we build on the basic skills learned here and look at some more practical applications for VBA.

Share This

Share This

Share this post with your friends!