User Guide For Visual Basic (VBA) In Microsoft Word – Mistakes To Avoid And A Step-By-Step Process

MS Office and in particular Microsoft Word have been created with a Visual Basic (typically VBA or sometimes VB) code language which tells the respective programs what to do. The code language has been gathered into a Visual Studio package containing other Microsoft software codes, wherein the VBA code language can be utilized in Microsoft Word to optimize the documents, running so-called macros or essentially shortcuts to make the documents more effective. After researching online, I have found that there has been a lack of Step-By-Step Processes for VBA in Microsoft Word, and I hope that this article proves useful to you.

Figure 1: Photo by Microsoft on Visual Studio Homepage

The steps to develop a macro-enabled document is included below:

1. To get started, open Microsoft Word. Open Microsoft Developer by following the below steps [1]:

  • On the File tab, go to Options Customize Ribbon.
  • Under Customize the Ribbon and under Main Tabs, select the Developer check box.

This gives the ability to create your own codes, macros and shortcuts amongst other useful functions.

2. Personally, I have spent a lot of time to understand why the macros sometimes do not work:

When saving the document, it will automatically become a ‘macro-enabled’ document with a .docm file extension. The macro-enabled term is used for a document which allows macros or shortcuts to run.

3. For the safety of your own Windows PC, only run macros you trust. If a notification comes up (TrustCenter), keep in mind that unsafe macros may run if the security of the document or your computer is not established. Be careful when opening documents online as viruses may run.

4. Insert codes or investigate codes using ‘macro recordings’, as this may allow to see certain operations done in word, which can be translated into codes and re-run to run shortcuts. This is a good way of saving time and being efficient.

5. When writing the VBA code itself, write it with small steps, explaining the code with a percentage in the beginning. If this is difficult for you, I advise that you create a so-called pseudocode, by breaking into as small steps as possible. This information was given to me by a fellow colleague, which I have found to be very useful.

The principle of the pseudocode is is to know what you are developing a code for and why. This step will also be essential if you end up having an error or several within a relatively large list of codes or if you get lost in what they mean or why you are doing them.

6. Run the codes by pressing the green “Run” (Play) button from the developer toolbar.

7. This last information about the file data, saving and testing is a small, but highly important step:

Keep your document a macro-enabled document (docm-format ending with ‘.docm’) without special characters and long file names, as this might complicate the codes the file has to run.

Such special characters includes the bracket parentheses (‘[]’), thus unfortunately it would be best to refrain from using these. Click Save AS and type .docm or select “Macro-enabled document” under filetype.

Test out the macro either within the developer interface or within the document if it is possible to execute it from there. If this is successful, try to re-open the file and test it again. If it runs without any errors, the macro-enabled document has been successful.

display monitor turning on

Figure 2: Photo by Pankaj Patel on Unsplash

I hope that these 7 steps on creating, developing and saving a ‘macro-enabled’ document have been useful. Below are some basic commands and some more complicated examples to get you started with implementing certain functions into your Microsoft Word document using the Visual Basic coding language.

Microsoft Word VBA Commands

Key

<Type in text> Refers to text that needs to be typed in, for example: Selection.TypeText Text:=”<Type in text>” could be Selection.TypeText Text:=”Hello World!”

‘<’ and ‘>’ symbols indicate a type field with start of the field and stop of the field respectively.

List of Basic Commands

Start and Stop

Start macro code with:

Sub <Type in text: Name of document>

End macro code with:

End Sub

Select

Select all text fields in the document:

Selection.WholeStory

Type or Print Statement

Type in text at an arbitrary or particular point in the document:

Selection.TypeText Text:=”<Type in text>

Type in a paragraph or space:

Selection.TypeParagraph

Create a textbox

Selection.CreateTextbox

Open a message box, a dialog box that has an “OK” button to click before proceeding:

MsgBox (“<Type in text>“)

If Statement

If <Type command>

End If

With Statement

With <Type command>

End With

List of Examples and More Complex Commands

Example 1: Hide all text in the document

Selection.WholeStory

    With Selection.Font

        .Name = “”

        .Hidden = True

Example 2: Unhide all text in the document

Selection.WholeStory

    With Selection.Font

        .Name = “”

        .Hidden = False

    End With

Example 3: Run a macro once checkbox is ticked

If  OptionButton1.Value = True  Then

<Type in command>

End If

Example 4: Once a checkbox is checked it results in sections of text to be hidden

Private Sub OptionButton1_Click()

If OptionButton1.Value = True Then

Selection.WholeStory

    With Selection.Font

        .Name = “”

        .Hidden = False

    End With

‘ Selects Page 3 “Section 3” (rectangle being the line below the selected point, remaining):

ActiveWindow.Panes(2).Pages(3).Rectangles(6).Range.Select

    With Selection.Font

        .Name = “”

        .Hidden = True

        End With

End If

MsgBox (“You can now continue with current Section 2.”)

End Sub

Private Sub OptionButton2_Click()

If OptionButton2.Value = True Then

Selection.WholeStory

    With Selection.Font

        .Name = “”

        .Hidden = False

    End With

ActiveWindow.Panes(2).Pages(2).Rectangles(7).Range.Select

    With Selection.Font

        .Name = “”

        .Hidden = True   

        End With    

End If

MsgBox (“You can now continue with current Section 2.”)

MsgBox (“Section 3 has also been updated to match your selection.”)

End Sub

Private Sub OptionButton3_Click()

If OptionButton3.Value = True Then

Selection.WholeStory

    With Selection.Font

        .Name = “”

        .Hidden = False

    End With

ActiveWindow.Panes(2).Pages(2).Rectangles(7).Range.Select

    With Selection.Font

        .Name = “”

        .Hidden = True      

        End With

End If

MsgBox (“You can now continue with current Section 2.”)

MsgBox (“Section 3 has also been updated to match your selection.”)

End Sub

Private Sub OptionButton5_Click()

‘Extra option button if needed within the document

End Sub

Example 5 (Final Example): Hide Specific “Bookmarked” Sections

Private Sub OptionButton1_Click()

If OptionButton1.Value = True Then

‘Unhides all:

Selection.WholeStory

    With Selection.Font

        .Name = “”

        .Hidden = False

    End With

‘GoTo Function works by: <expression. GoTo( _What_ , _Which_ , _Count_ , _Name_ )> ‘Thus, we need to input a name for our bookmark. This has to be done manually before running the code. ‘(1) Go to the word document. (2) Mark the text/table/object that you need to hide is marked up. ‘(3) Go to the Ribbon and go to Insert tab. ‘(4) Click on the “Bookmark” logo under the ‘Fields’ collection. ‘(5) Start writing the name of your bookmark such as: (Table1) or (Bookmark1) etc. ‘(6) Apply the following code and input the Name:=”” between the “”. ‘(7) Run the code. ‘Hides bookmarked section by making sure bookmark is unhidden:

Selection.GoTo What:=wdGoToBookmark, Name:=”Section3_6″

    ‘Makes sure all bookmarks are unhidden:

    With ActiveDocument.Bookmarks

        .DefaultSorting = wdSortByName

        .ShowHidden = False

    End With

    ‘Hides selection:

    With Selection.Font

        .Name = “”

        .Hidden = True

    End With

    End If

MsgBox (“You can now continue with current Section 2.”)

End Sub

Private Sub OptionButton3_Click()

If OptionButton3.Value = True Then

‘Unhides all:

    Selection.WholeStory

        With Selection.Font

            .Name = “”

            .Hidden = False

        End With

‘GoTo Function works by: <expression. GoTo( _What_ , _Which_ , _Count_ , _Name_ )> ‘Thus, we need to input a name for our bookmark. This has to be done manually before running the code. ‘(1) Go to the word document. ‘(2) mark the text/table/object that you need is marked up. ‘(3) Go to the Ribbon and go to Insert. ‘(4) Click on the “Bookmark” logo under the ‘Fields’ tab. ‘(5) Start writing the name of your bookmark such as: (Table1) or (Bookmark1) etc. ‘(6) Apply the following code and input the Name:=”” between the “”. ‘(7) Run the code. ‘Hides bookmarked section by making sure bookmark is unhidden:

Selection.GoTo What:=wdGoToBookmark, Name:=”Section1_6″

    ‘Makes sure all bookmarks are unhidden:

    With ActiveDocument.Bookmarks

        .DefaultSorting = wdSortByName

        .ShowHidden = False

    End With

    ‘Hides selection:

    With Selection.Font

        .Name = “”

        .Hidden = True

    End With

‘Additional block Table3_2 removed

Selection.GoTo What:=wdGoToBookmark, Name:=”Table3_2″

    ‘Makes sure all bookmarks are unhidden:

    With ActiveDocument.Bookmarks

        .DefaultSorting = wdSortByName

        .ShowHidden = False

    End With

    ‘Hides selection:

    With Selection.Font

        .Name = “”

        .Hidden = True

    End With

End If

MsgBox (“You can now continue with current Section 2.”)

MsgBox (“Section 3 has also been updated to match your selection.”)

End Sub

I hope that you find these examples useful. If you have any comments or questions, feel free to let me know under the Contact tab or as a comments below. Thank you for visiting!


Sources

[1] MIcrosoft Office, 2021. [Online].Available: https://support.microsoft.com/en-us/office/show-the-developer-tab-in-word-e356706f-1891-4bb8-8d72-f57a51146792

Leave a Comment

Your email address will not be published.