A P P E N D I X    B Microsoft Office 97/Visual Basic Programmer's Guide

Switching from WordBasic


Contents

This appendix is intended to help users switching from the WordBasic programming language to Visual Basic for Applications, the new programming language in Microsoft Word 97 (and other Office 97 applications).

The first step toward making this switch is to convert your existing WordBasic macros. For information about converting your WordBasic macros, see "Converting WordBasic macros to Visual Basic" in Help. This Help topic explains how Word automatically converts macros in Word 6.x or Word 95 templates to Visual Basic.

Although Word converts your macros, you may need to modify parts of them manually to retain the macros' original functionality. In addition to making modifications to converted WordBasic macros, you may need to write new macros in the future. It's possible to continue using WordBasic statements and functions exposed through the WordBasic object, but gradually you'll want to switch over to Visual Basic. For information about the functionality available with Visual Basic, see the introduction in this book.

To help make the switch to Visual Basic an easy one, a table of WordBasic commands and their corresponding Visual Basic syntax is included in Help, in the topic "Visual Basic Equivalents for WordBasic Commands."

Logistical Programming Changes in Microsoft Word 97

The introduction in this book discusses the capabilities of Visual Basic. The following paragraphs supplement the information provided in the introduction with references to previous versions of Word.

Macro Editor   The built­in macro editor in previous versions of Word has been replaced by an integrated Visual Basic development environment, which is referred to as the Visual Basic Editor. The Visual Basic Editor runs in its own window and looks exactly the same no matter which Office application you start it from.

Dialog Editor   Previous versions of Word included a separate Dialog Editor application used to design custom dialog boxes. You create custom dialog boxes in Word 97 by creating UserForms in the Visual Basic Editor. For more information about UserForms, see Chapter 12, "ActiveX Controls and Dialog Boxes."

Macro Storage   When you create a new macro in the Macros dialog box in Word (point to Macro on the Tools menu, and then click Macros), a new subroutine with the macro name you provide is created in a module. Macros can now be stored in documents as well as templates. You specify the storage location by selecting an item in the Macros in box in the Macros dialog box. The Macros in box includes template names and the name of the active document (for example, "Sales.doc (document)").

Conceptual Differences Between WordBasic and Visual Basic

The primary difference between Visual Basic and WordBasic is that WordBasic consists of a flat list of approximately 900 commands, whereas Visual Basic consists of a hierarchy of objects, each of which exposes a specific set of methods and properties (similar to statements and functions in WordBasic). Objects are the fundamental building block of Visual Basic; almost everything you do in Visual Basic involves modifying objects. Every element of Word — documents, paragraphs, fields, bookmarks, and so on — is represented by an object in Visual Basic. To view a graphical representation of the object model for Word, see "Microsoft Word Objects" in Help.

Whereas most WordBasic commands can be run at any time, Visual Basic instructions drill down through the object model to an object that you can manipulate using properties and methods. There are certain objects that you can get to only from other objects — for instance, the Font object, to which you can control from the Style, Selection, or Find object, among others. Before you can change any font­related attributes (such as bold formatting), you need to drill down to the Font object.

The programming task of applying bold formatting demonstrates one of the differences between the two programming languages. The following WordBasic example applies bold formatting to the selection.

Bold 1

Visual Basic doesn't include a Bold statement and function; instead, there's a Bold property (a property is usually an attribute of an object, such as its size, its color, or whether or not it's bold). The Bold property is a property of the Font object, which is returned by the Font property. The Font property is a property of the Selection object, which is returned by the Selection property. And finally, the Selection property is a property of the Application object, which is returned by the Application property. These relationships are shown in the following object hierarchy.

Using this object hierarchy, you can build the instruction shown in the following example to apply bold formatting to the selection.

Application.Selection.Font.Bold = True

Note   Because the Selection property is "global," the Application property is optional. To view a list of all the global properties and methods, click <globals> at the top of the Classes list in the Object Browser.

Instead of being composed of a flat list of commands, Visual Basic consists of a hierarchical arrangement of objects that support a predefined set of properties and methods (as shown in the preceding illustration). The following table shows some common WordBasic instructions and their Visual Basic equivalents.

WordBasic instruction Equivalent Visual Basic instruction
FileOpen .Name = "MYDOC.DOC" .Documents.Open FileName:= "MYDOC.DOC"
Insert "new text" Selection.TypeText Text:="new text"
Activate "Document1" Windows("Document1").Activate
MsgBox Font$() MsgBox Selection.Font.Name
FormatParagraph .Alignment = 3 Selection.Paragraphs.Alignment = wdAlignParagraphJustify

The two instructions in each row of the preceding table are functionally equivalent, but their syntax is dramatically different. Each WordBasic instruction consists of a command name (for example, FileOpen) and any applicable arguments (for example, .Name). Each Visual Basic instruction, on the other hand, is a combination of one or more properties or methods (for example, Documents and Open), followed by any applicable arguments for each (for example, FileName). The properties and methods you use to drill down through the object model are separated by the dot operator.

The Open method in Visual Basic is functionally equivalent to the WordBasic FileOpen statement when the Open method is used with the Documents collection object. The Documents collection is returned by the Documents property. The following illustration shows the path to the Open method.

Following this hierarchy, you can build the instruction shown in the following example to open Mydoc.doc.

Application.Documents.Open FileName:="MYDOC.DOC"

Note   The Application property is optional because the Documents property is "global."

Visual Basic doesn't include separate statements and functions as in WordBasic. The Bold property is a read/write Boolean property. This means that the Bold property can be set to either True or False (on or off), or the current value can be returned. The following table shows the Visual Basic equivalents for various versions of the WordBasic Bold statement and the WordBasic Bold function.

WordBasic Bold statement or function Equivalent Visual Basic instruction
Bold 1 Selection.Font.Bold = True
Bold 0 Selection.Font.Bold = False
Bold Selection.Font.Bold = wdToggle
x = Bold() x = Selection.Font.Bold

Determining Which Properties or Methods to Use

There are a few techniques you can use to determine which Visual Basic properties or methods you need to use to accomplish a particular programming task. When you're first learning Visual Basic, it's usually best to use the macro recorder. The macro recorder is a tool that translates your actions into Visual Basic instructions. For instance, if you turn on the macro recorder and open the document named "Examples.doc" in the current folder, the macro recorder records the following instruction.

Documents.Open FileName:="Examples.doc", ConfirmConversions:=False, _
    ReadOnly:=False, AddToRecentFiles:=False, PasswordDocument:="", _
    PasswordTemplate:="", Revert:=False, WritePasswordDocument:="", _
    WritePasswordTemplate:="", Format:=wdOpenFormatAuto

To learn more about the preceding instruction, position the insertion point within the word "Open" and then press F1. The Help topic for the Open method explains the arguments you can use with that method. For information about the Documents property, position the insertion point within the word "Documents" and then press F1.

Until you become somewhat familiar with the Word object model, there are a few tools and techniques you can use to help you drill down through the object hierarchy.

Auto List Members   When you type the dot operator after a property or method in the Visual Basic Editor, a list of available properties and methods is displayed. For example, if you type Application., a list containing methods and properties of the Application object is displayed. Select the method or property you want to use, and then press TAB to insert the selected item.

Visual Basic Help   You can use Help to find out which properties and methods you can use with a particular object. Each object topic in Help includes a Properties jump and a Methods jump, which display (respectively) a list of properties and a list of methods for the object. To jump to the appropriate Help topic, press F1 in the Object Browser or a module.

Object model   For an illustration of how Word objects are arranged in the object hierarchy, see "Microsoft Word Objects" in Help. Click an object in the graphic to display its corresponding Help topic.

Object Browser   The Object Browser in the Visual Basic Editor displays the members (properties and methods) of the Word objects.

Using the Object Browser

To perform a task in Visual Basic, you need to determine the appropriate object to use. For example, if you want to apply character formatting found in the Font dialog box, use the Font object. Then you need to determine how to drill down through the Word object hierarchy from the Application object to the Font object, through the objects that contain the Font object you want to modify.

To see how this is done, open the Visual Basic Editor and click Object Browser on the View menu. Click Application in the Classes list. then click Selection in the Members list. The text at bottom of the Object Browser indicates that Selection is a read­only property that returns a Selection object. Click Selection at the bottom of the Object Browser; Selection is now selected in the Classes list, and the Members list displays the members of the Selection object. Scroll through the list of members until you find Font, and then click Font. The text at the bottom of the Object Browser indicates that Font is a read­only property that returns a Font object. Click Font at the bottom of the Object Browser; Font is now selected in the Classes list, and the Members list displays the members of the Font object. Click Bold in the Members pane. The text at the bottom of the Object Browser indicates that the Bold property is a read/write property. For more information about this property, press F1 or click the Help button to jump to the Help topic for the Bold property.

Given this information, you can write the instruction shown in the following example to apply bold formatting to the selection.

Selection.Font.Bold = True

As you can see, you use methods or properties to drill down to an object. That is, you return an object by applying a method or property to an object above it in the object hierarchy. After you return the object you want, you can apply the methods and control the properties of that object.

Note   A given object often exists in more than one place in the object hierarchy. For an illustration of the Word object model, see "Microsoft Word Objects" in Help. Also, individual properties and methods are often available to multiple objects in the Word object hierarchy. For example, the Bold property is a property of both the Font and Range objects. The following example applies bold formatting to the entire active document (the Content property returns a Range object).

ActiveDocument.Content.Bold = True

Selection Object vs. Range Object

Most WordBasic commands modify whatever is selected. For example, the Bold command formats the selection with bold formatting, and the InsertField command inserts a field at the insertion point. Visual Basic supports this same functionality through the Selection object, which you return by using the Selection property. The selection can be a block of text or just the insertion point.

The following Visual Basic example inserts the text "Hello World" and a new paragraph after the selection.

Selection.InsertAfter Text:="Hello World"
Selection.InsertParagraphAfter

In addition to working with the selection, you can define and work with various ranges of text in a document. A Range object refers to a contiguous area in a document, with a starting character position and an ending character position. Similar to the way you use bookmarks in a document, you use Range objects in Visual Basic to identify portions of a document. For example, you can use Visual Basic to apply bold formatting anywhere in a given document without changing the selection. The following example applies bold formatting to the first 10 characters in the active document.

ActiveDocument.Range(Start:=0, End:=10).Bold = True

The following example applies bold formatting to the first paragraph.

ActiveDocument.Paragraphs(1).Range.Bold = True

Both of the preceding example change the formatting in the active document without changing the selection. In most cases, Range objects are preferred over the Selection object for the following reasons:

  • You can define and use multiple Range objects, whereas you can have only one Selection object per document window.

  • Manipulating Range objects doesn't change the selection.

  • Manipulating Range objects is faster than working with the selection.

For more information about working with Range and Selection objects, see Chapter 7, "Microsoft Word Objects."

Using WordBasic Statements and Functions

You can use WordBasic statements and functions in your Visual Basic macros. When you use a WordBasic macro in Word 97, the macro is automatically modified to work with Visual Basic. The following example is a WordBasic macro in a Word 95 template.

Sub MAIN
FormatFont .Name = "Arial", .Points = 10
Insert "Hello World"
End Sub

When the template is opened in Word 97, the macro is converted to the code shown in the following example.

Public Sub Main()
WordBasic.FormatFont Font:="Arial", Points:=10
WordBasic.Insert "Hello World"
End Sub

Each statement in the converted macro begins with the WordBasic property. The WordBasic property returns an object with methods that correspond to the WordBasic statements and functions; this object makes it possible to run WordBasic macros in Word 97. You can reuse old code (instructions that use the WordBasic property) along with new instructions that you write (instructions that don't use the WordBasic property). The following example is functionally equivalent to the preceding macro; however, the second WordBasic instruction has been changed to use the TypeText method of the Selection object.

Public Sub Main()
WordBasic.FormatFont Font:="Arial", Points:=10
Selection.TypeText Text:="Hello World"
End Sub

Using WordBasic Statements

If you still want to use WordBasic statements in Word 97, precede each WordBasic statement with the WordBasic property followed by the dot operator. The following Visual Basic example moves the insertion point to the beginning of the document.

WordBasic.StartOfDocument

The following example sets justified paragraph alignment and adds 1 inch of space above and below each paragraph in the selection.

WordBasic.FormatParagraph .Alignment = 3, .Before = "1 in", .After = "1 in"

The following example selects all text from the insertion point through the MyMark bookmark. (Notice how the With statement is used to specify the WordBasic object once for a series of instructions.)

With WordBasic
    .ExtendSelection
    .EditGoTo "MyMark"
    .Cancel
End With

Using WordBasic Functions

Likewise, to use WordBasic functions in Word 97, precede the WordBasic function with the WordBasic property followed by the dot operator, and use square brackets around the function name. The following table shows the original WordBasic syntax and the corresponding Visual Basic syntax using the WordBasic property.

WordBasic instructions Equivalent Visual Basic instruction
MsgBox Font$() MsgBox WordBasic.[Font$]()
If Bold() = 0 Then Bold 1 If WordBasic.[Bold]() = 0 Then WordBasic.Bold 1
x = AppInfo$(1) x = WordBasic.[AppInfo$](1)

Note   Methods of the WordBasic object are slower than methods and properties of other Visual Basic objects. For example, WordBasic.FileOpen is slower than Documents.Open. Also, the WordBasic language won't be updated with new commands in the future. Visual Basic includes objects, properties, and methods that duplicate and improve on WordBasic functionality. If you know which WordBasic command to use to perform a particular task, see the conversion table in "Visual Basic Equivalents for WordBasic Commands" in Help. This will give you a guide as to which Visual Basic methods and properties to use for specific tasks.

Miscellaneous Changes

This section outlines other changes to the programming environment in Word 97.

Syntax Changes

Use the dot operator (.) to separate properties and methods in a Visual Basic instruction. The following example makes the selected text red. The example uses dots to separate the Selection, Font, and ColorIndex properties.

Selection.Font.ColorIndex = wdRed

Use an equal sign (=) to set property values. The following example makes the first paragraph in the active document bold.

ActiveDocument.Paragraphs(1).Range.Bold = True

Use a colon followed by an equal sign (:=) to set an argument of a method, and use a comma to separate arguments of a method. The following example opens MyDoc.doc as a read­only document. FileName and ReadOnly are arguments of the Open method.

Documents.Open FileName:="C:\MyFiles\MyDoc.doc", ReadOnly:=True

Use a space followed by an underscore character ( _) to continue a Visual Basic instruction to the next line. (In WordBasic, the continuation character is a backslash character (\).) The following Visual Basic example spans three lines. The first and second lines end with continuation characters. Press ENTER after typing the continuation character.

Documents.Open FileName:="C:\MyFiles\MyDoc.doc", _
    ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=True, _
    Revert:=False, Format:=wdOpenFormatAuto

Data Types

Visual Basic has many more data types than does WordBasic. You can define and use variables without learning about data types, but if you want to write efficient code you should define variables with the appropriate data type (for instance, Integer, String, or Long). The following example defines the counter variable as an integer.

Dim counter As Integer

If you don't specify a data type when you define a variable, Visual Basic automatically specifies the Variant data type, which takes up the largest amount of memory (a minimum of 16 bytes) of all the data types. For information about the various Visual Basic data types, see Chapter 1, "Programming Basics," or see "Data Type Summary" in Help.

Concatenating Strings and Inserting Special Characters

Use the ampersand character (&) instead of a plus sign (+) to concatenate strings. To insert special characters, you can continue to use the Chr$() function in Word 97, or you can use one of the following constants: vbCr, vbLf, vbCrLf, or vbTab. The following table shows WordBasic instructions that use concatenated strings and special characters, and their Visual Basic equivalents.

WordBasic instruction Equivalent Visual Basic instruction
Insert "Hamlet " + Chr$(13) Selection.InsertAfter Text:="Hamlet " & vbCr
Msgbox "Hello" + Chr$(32) + "Tom" MsgBox Text:="Hello" & Space & "Tom"
Insert Chr$(9) Selection.InsertAfter Text:=vbTab

Note   Use the ChrW$() function to return a string that contains the character associated with the specified Unicode character.

Loops and Conditional Statements

Visual Basic and WordBasic have similar conditional and looping statements (also known as control structures). Visual Basic includes additional looping statements, which are marked with an asterisk in the following table. For information about using the conditional and looping statements in the following table, see Chapter 1, "Programming Basics."

StatementPurpose
If...Then...Else Branching when the specified condition is True or False
Select Case Selecting a branch from a set of conditions
Do...Loop* Looping while or until the specified condition is True
While...Wend Looping while the specified condition is True (same as the Do While…Loop form of Do…Loop)
For...Next Repeating a group of instructions a specified number of times
For Each...Next* Repeating a group of instructions for each object in the specified collection

Visual Basic includes a For...Next statement for looping through a series of instructions. For looping through objects in a collection, however, the For Each…Next statement works more efficiently. The following WordBasic example creates a new document and then inserts the available font names.

FileNewDefault
For count = 1 To CountFonts()
    Insert Font$(count)
    InsertPara
Next count

The following Visual Basic example is an equivalent for the preceding WordBasic example. Notice how the With statement is used to specify the Selection object once for a series of instructions.

Documents.Add
For i = 1 To FontNames.Count
    With Selection
        .InsertAfter Text:=FontNames(i)
        .InsertParagraphAfter
        .Collapse Direction:=wdCollapseEnd
    End With
Next I

The For Each…Next statement automatically loops through each item in the collection without using a counter variable that the For…Next statement requires. The following Visual Basic example is also an equivalent for the preceding WordBasic example. However, it is more efficient than the preceding Visual Basic equivalent, which uses For…Next.

Documents.Add
For Each aFont In FontNames
    With Selection
        .InsertAfter Text:=aFont
        .InsertParagraphAfter
        .Collapse Direction:=wdCollapseEnd
    End With
Next aFont

Measurements

Often you can specify measurements in WordBasic macros either in points or as a text measurement (that is, a measurement specified as a string). For example, the following WordBasic example sets justified alignment and adds 1 inch of space above and below each paragraph in the selection (1 inch = 72 points).

FormatParagraph .Alignment = 3, .Before = 72, .After = "1 in"

The following Visual Basic example is equivalent to the preceding WordBasic statement. The With statement is used to specify the Paragraphs collection object once for a series of instructions that set properties of the Paragraphs collection.

With Selection.Paragraphs
    .Alignment = wdAlignParagraphJustify
    .SpaceBefore = 72
    .SpaceAfter = InchesToPoints(1)
End With

You must specify measurements for Word methods and properties in points. You can do this either by specifying the number of points as a number or by using one of the following conversion methods to convert the measurement to points: CentimetersToPoints, InchesToPoints, LinesToPoints, MillimetersToPoints, or PicasToPoints. The preceding example uses the InchesToPoints method to convert 1 inch to points.

Example Macros

This section provides some WordBasic and Visual Basic macros for comparison.

Applying Formatting

The following WordBasic macro applies character and paragraph formatting to the selected text.

Sub MAIN
FormatFont .Font = "Times New Roman", .Points = 14, .AllCaps = 1
FormatParagraph .LeftIndent = "0.5"
SpacePara1
End Sub

The following Visual Basic macro is the equivalent of the preceding WordBasic macro. This macro uses the Selection property to apply character and paragraph formatting to the selected text. It uses the Font property to gain access to character­formatting properties, and it uses the ParagraphFormat property to gain access to paragraph­formatting properties and methods.

Sub Macro1()
With Selection.Font
    .Name = "Times New Roman"
    .Size = 14
    .AllCaps = True
End With
With Selection.ParagraphFormat
    .LeftIndent = InchesToPoints(0.5)
    .Space1
End With
End Sub

Deleting to the Beginning of a Sentence

The following WordBasic macro deletes the text between the insertion point and the beginning of the sentence that the insertion point is positioned within. The macro then capitalizes the first letter of the remaining text.

Sub MAIN
SentLeft 1, 1
EditCut
ChangeCase 4
End Sub

The following Visual Basic macro uses the MoveStart method to extend the selection to the beginning of the active sentence. The Cut method cuts the selected text and places it on the Clipboard, and the Case property changes the capitalization of the character following the selection.

Sub Macro1()
With Selection
    .MoveStart Unit:=wdSentence, Count:=-1
    .Cut
    .Range.Case = wdTitleSentence
End With
End Sub

Removing Excess Paragraph Marks

Some sources of text include a paragraph mark at the end of every line. This text is difficult to work with in Word because Word treats each line as a separate paragraph and doesn't wrap the text. The following WordBasic macro removes the excess paragraph marks (the end­of­line paragraph marks) but leaves the end­of­paragraph marks.

Sub MAIN
EditReplace .Find = "^p^p", .Replace = "@#$#", \
    .Direction = 0, .ReplaceAll, .Format = 0, .Wrap = 1
FileSave
EditReplace .Find = "^p", .Replace = " ", \
    .Direction = 0, .ReplaceAll, .Format = 0, .Wrap = 1
FileSave
EditReplace .Find = "@#$#", .Replace = "^p^p", \
    .Direction = 0, .ReplaceAll, .Format = 0, .Wrap = 1
End Sub

The preceding macro assumes that two consecutive paragraph marks signify the end of a paragraph. When you remove paragraph marks from text, you usually want to preserve separate paragraphs. For that reason, this macro replaces two consecutive paragraph marks with the placeholder "@#$#". The macro then replaces each remaining paragraph mark with a space. Finally, it replaces the "@#$#" placeholder with two paragraph marks.

The following Visual Basic macro is the equivalent of the preceding WordBasic macro. The macro uses the Execute method of the Find object to execute the three find and replace operations. It uses the Save method to save the active document after each find and replace operation.

Sub Macro1()
With Selection.Find
    .Execute FindText:="^p^p", ReplaceWith:="@#$#", Wrap:=wdFindContinue, _
        Replace:=wdReplaceAll, Format:=False, Forward:=True
    ActiveDocument.Save
    .Execute FindText:="^p", ReplaceWith:=" ", Wrap:=wdFindContinue, _
        Replace:=wdReplaceAll, Format:=False, Forward:=True
    ActiveDocument.Save
    .Execute FindText:="@#$#", ReplaceWith:="^p^p", Wrap:=wdFindContinue, _
        Replace:=wdReplaceAll, Format:=False, Forward:=True
End With
End Sub

Counting How Many Times a Word Appears

The following WordBasic macro uses a While...Wend loop to count the number of times that a specified word appears in a document. The InputBox$() function prompts the user for a search word.

Sub MAIN
count = 0
True = -1
searchtext$ = InputBox$("Please type a word to search for:")
StartOfDocument
EditFind .Find = searchtext$, .Direction = 0, .MatchCase = 0, \
    .WholeWord = 0, .Format = 0, .Wrap = 0
While EditFindFound() = True
    count = count + 1
    RepeatFind
Wend
MsgBox searchtext$ + " was found " + count + " times"
End Sub

The following Visual Basic macro accomplishes the same task as the preceding WordBasic macro by using a Do...Loop statement and the Execute method of the Find object. Because the macro gets to the Find object from a Range object (the Content property returns a Range object), the selection in the document is unchanged. Each time the specified word is found, the count variable is incremented by 1. As soon as the Do…Loop statement finishes looping through the document (that it, when it has counted all instances of the specified word), the macro exits the loop and displays the results in a message box.

Sub Macro1()
count = 0
searchtext$ = InputBox$("Please type a word to search for:")
With ActiveDocument.Content.Find
    Do While .Execute(FindText:=searchtext$, Format:=False, _
            MatchCase:=False, MatchWholeWord:=False) = True
        count = count + 1
    Loop
End With
MsgBox searchtext$ & " was found " & count & " times"
End Sub