Resting Anchor

The Anchorage

Personal website of Gregory K. Maxey, Commander USN (Retired)

VBA Basics Exercise Tutorial
(A Microsoft Word Help & Tip page by Gregory K. Maxey)

DISCLAIMER/TERMS OF USE

The information, illustrations and code contained in my "Microsoft Word Tips" are provided free and without risk or obligation.

Click to acces PayPal Verification Service Click to acces PayPal Verification Service

However, the work is mine. If you use it for commercial purposes or benefit from my efforts through income earned or time saved then a donation, however small, will help to ensure the continued availability of this resource.

If you would like to donate, please use the appropriate donate button to access PayPal. Thank you!

Click to donate British Pound Sterling                   Click to donate US dollars                   Click to donate EU euros

This Microsoft Word Tips & Microsoft Word Help page supplements my VBA Basics tips page and provides a structured exercise to enhance your understanding of VBA Basics.

Completing this exercise will not make you a VBA expert but it should guide your exploration of VBA in a way that you find helpful.  The following steps, depending on your pace, should take between 15 to 30 minutes.  When completed, you can congratulate yourself, because you have have taken some initial steps towards understanding VBA and you should have a feel for what it is like to program in Word.

To get started, launch Word and press Alt+F11 to expose the Visual Basic Editor (VBE).

1.  Using the VBE menu, click Tools>Options and set the Editor options.  I recommend (and practice) using all the editor options as shown below:

vba_basic_tutorial_1

Site Note IconNote: The vast majority of code samples you find on web will use a tab width (used for indenting) set to 4. Either to be different or obstinate, I prefer 2.

2. If not already displayed, press Shift+F7 to display the Code window.

vba_basics_tutorial_2

3. Put the cursor on the line under "Option Explicit" and type the following then press enter.

vba_basics_tutorial_3

Press the Tab key once then type the following including the ending period or "dot"

Immediately after typing the period, notice that Auto List Members is triggered and displayed.

vba_basics_tutorial_4

When you want to VBA properties or methods to act on the document on screen (ActiveDocument), then you have to start this way.

In the members list your will find each property and method of the ActiveDocument object and any other objects that belongs to the ActiveDocument object.  The ActiveDocument is the thing or (object) you want to work with.

Methods

A method is an action or something that can do to or with the the ActiveDocument object.  To use a grammar analogy, a method is like a verb.  I (subject) print (verb) ActiveDocument (object).

With that idea in mind, scroll down the members list and see if you can find a method that  might suit the requirement to print the active document. You can distinguish the methods from the prosperities/object by the associated icons.  Methods are identified by a "action" icon that resembles a green block flying across the screen.

4. Apply the "PrintOut" method by either selecting the method and pressing the tab key or dbl-clicking the listed method.  Either way the object will take the method and the code line appears as:

vba_basics_tutorial_5

What next?  Are you finished?  You could be.  If all you want to do is print the active document and you don't care how Word performs the action then yes, you are done.

However, that is an overly simple exercise and not very much fun.  Lets say that you aren't done and want some say on how that print action is performed.

5. Type a space immediately following .PrintOut. As soon as you do, another extremely helpful listing is displayed similar to the following:

vba_basics_tutorial_6

These define the arguments associated with the PrintOut method.  If you look closely you may see that many of the arguments look similar to the options in the File>Print dialog you have used when printing a document through the normal user interface. For an explanation of the arguments and how to apply them, press F1.

There are two ways to apply the arguments:

Named arguments typically make your code far easier to read and you only have to be concerned and list the arguments you actually want to use.

Indexed arguments are typically faster for experienced developers to insert but they are clearly harder to read and you have to be concerned about and account for each argument between the first and last used.

6. Enter named arguments for Background and Copies. Your procedure should appear as follows:

VBA Script:
Sub DemoMacro()
  ActiveDocument.PrintOut Background:=False, Copies:=2
End Sub

7. Test your procedure either from within the VBE or the object document (or both) as follows:

vba_basics_tutorial_7
In the VBE, with the cursor in the DemoMacro procedure, press F5 or use the toolbar Run Sub button icon.

vba_basics_tutorial_8

From the active document object, use Developer>Code>Marcos
Select the macro and click "Run"

Properties

With methods, our line of thought was to DO something with the active document as whole (e.g., Print it, Save it, etc.). Moving on to properties, lets think about CHANGING some aspect or "property" of the active document as a whole.

8. Lets delete the existing single line of code between the Sub DemoMacro and End Sub. Then as before, press the tab key once and type:

Remember, ActiveDocument is the thing (object) you want to work with. Be sure to type the end period or "dot" and when you do, notice that Auto List Members is again triggered and displayed.

A property is a single characteristic of an object. One of the properties of a document object is its password.

 In the methods demonstration, I asked you to scroll down the list members until you found a method that might serve to print the active document. That is always an option, but now you already know that "Password" is a property of the ActiveDocument object.

9. Start to type Password and notice when you do how the Auto List Members seeks properties and methods starting with P, then narrows to Pa and finally after you type Pas the Password property is selected.  At this point, simple press the space key.

vba_basics_tutorial_9

Your line now looks like this:

You are clearly smart enough to know that something has to come next, but what?  The VBE has no idea what the document password should be and in this case pressing the space bar offers no clue what to do next.

In my opinion, if on your own, you would be in a position where I find working with VBA most enjoyable.  If  you don't know, then you need to use what you already know, experiment with the tools available, and discover what to do next.

Intuition is one of the primary tools in my VBA tool box.  If you are an intuitive thinker then you are likely to realize that the document password must be equal "=" to something and you as the developer will have to provide what that something is.

If a possible solution doesn't come to you intuitively then you may be able to determine the next step using the VBE tools.  One of those tools is the VBE compiler.  The compilers job is to ensure that whatever code you write or attempt to write is correctly structured.  The compiler won't run code that can't be run.

10.  Test to see if your procedure, as written will run.  With the cursor in the Sub DemoMacro procedure, attempt to step into your code by pressing the F8 key.

vba_basics_tutorial_10

Site Note IconNote: F8 initiates the "step into" method of debugging (finding and fixing problems in your code).  It can also be initiated using the VBE Debug menu. 

11.  With the problem selected as shown above, press the F1 key.

vba_basics_tutorial_11

Site Note Icon Note: If you pursue your quest to understand and use VBA, you will soon discover that many of the code examples in Microsoft help topics are incomplete and won't compile themselves. dunno

For this basic tutorial, we are going to ignore (for now) Microsoft's sound advice to avoid "hard-coded" passwords.  The take away is that the password property has to be set = to a value

12. Type: = "demoPW"

Be sure to enclose the literal password demoPW within quotation marks as shown. Your procedure should look like this. 

VBA Script:
Sub DemoMacro()
  ActiveDocument.Password = "demoPW"
End Sub

13.  Run the procedure as you did before by pressing F5. Or, since you now have more experience, try stepping into it using F8. This time you can press the F8 key three times and watch how each line of code is executed without error.

14. Test your project.  Save and close the active document.  Then reopen it.  You should be presented with a dialog to enter the password you defined.

Objects of ActiveDocument Collections

To this point we have focused on the ActiveDocument object as the thing we want to work with.  Well there are only so many things that you can DO to or CHANGE in the ActiveDocument object itself.

However, the ActiveDocument object consists of many of collections of other objects that we can discover through the ActiveDocument object and continue our VBA experience.

One such object is a single paragraph object in the ActiveDocument paragraph collection (all of the paragraphs). Remember, an object is something that you can "work on" by applying methods to it or by changing its properties.

15. In the document you are using with this tutorial enter a few short paragraphs of text.  It really doesn't matter what that text is, just ensure that you have created more that one paragraph as shown below.

vba_basics_tutorial_12

16.  Our line of thought now is that we want to work with a single paragraph object in the collection of paragraphs in the activedocument object.  As done previously, delete the single line of code between Sub DemoMacro() and End Sub, press the tab key once and type: 

17. Again, the Auto List Memebers is presented immediately after you type the "." (dot). You can scroll down the list as before and look for a suitable collection object.  But, since you know that "Paragraphs" exists (you typed them), it is much easier to simply start typing Par ...

When you do, the VBE will soon drill down and Paragraphs is selected.

vba_basics_tutorial_13

There are two ways to proceed from this point. The first, which based on your experience so far may be intuitive, is to type a period (dot) and see what the Auto List Members will offer. The second is to think about what a collection is and discover a different way.

A collection object is a collection of things (other objects) that can be counted.  The paragraph collection in the activedocument that I used for this demonstration is a collection of three paragraphs (yours may be more or less) and counted (or indexed) 1, 2 and 3.

18. Indexed items in a collection can be defined by placing the index number of the item in parenthesis.  With this in mind, append "(2)" to your code line as shown below:

This tells the VBE (the compiler) that the object you want to work with is the second paragraph object in the paragraphs collection object of the activedocument object.  Getting the picture?

19. You've got the object you want to work with so now just type a period and let the Auto List Members trigger and show you all the methods, properties and objects associated with the paragraph object.

vba_basics_tutorial_14

Site Note IconNote: Microsoft, for whatever reason, does not differentiate between a property and object (with icons).  In the short list shown above, Borders is clearly a collection object as it consists of the top, left, right, bottom, etc. border (things that can be counted and indexed) of a paragraphs borders.

20.  Just for fun, lest carry this on a bit.  Select "Alignment" an press the space bar.

Has experience taught you what to do next? think Do you think this line of code will compile? thinking  As with the activedocument property "Password," the paragraph property needs a value.  To set the value, type the = sign and smile with pleasure when you discover this time the VBE is there to help!

vba_basics_tutorial_15

21. To this point we have doggedly had in our mind that we would be doing something to or with the activedocument object or an object in one of the activedocument object collection objects.  You can spend the rest of your day (or life for that matter) learning and discovering about the VBE and Word object model. Now or later you might come back to this page and instead of staring with the ActiveDocument oject, start with the Application or Selection object.

Here is a small teaser:

vba_basics_tutorial_16

Conclusion

Earlier I said lets ignore Microsoft's sound advice concerning using "hard-coded" passwords in your code.  Since I don't want to leave you will "negative" teaching, I want to provide a short code sample for you do see how to apply that advice in a functional procedure.  This will introduce your to VBA "Functions" which is covered in more detail in my VBA Basics

VBA Script:
Option Explicit
Sub DemoMacro()
'Declare a variable "strPassword" as a variable type string
Dim strPassword As String
  'Use the VBA Function InputBox
  strPassword = InputBox("Enter the password to assign", "PASSWORD")
  ActiveDocument.Password = strPassword
  'Notes:
  'The green text represents comment text (compiler ignores).
  'Comments are created by starting the line with the stet character "'"
  'Option Explicit at the top of the code module "forces" you to declare variables.
End Sub

That's it! I hope you have found this tips page useful and informative.

Share

DISCLAIMER/TERMS OF USE

The information, illustrations and code contained in my "Microsoft Word Tips" are provided free and without risk or obligation.

Click to acces PayPal Verification Service Click to acces PayPal Verification Service

However, the work is mine. If you use it for commercial purposes or benefit from my efforts through income earned or time saved then a donation, however small, will help to ensure the continued availability of this resource.

If you would like to donate, please use the appropriate donate button to access PayPal. Thank you!

Click to donate British Pound Sterling                   Click to donate US dollars                   Click to donate EU euros

Search my site or the web using Google Search Engine

Google Search Logo