This documentation is archived and is not being maintained.

Handy Tips When Using Word 2003

Office 2003

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

Summary: Looking for tips to help when developing in Microsoft Word? This article consists of a compilation of various tips from the Microsoft Word newsgroups. By using these procedures and modifying them for your own use, you can make your own applications more robust and provide more options to your users. (8 printed pages)

This article presents tips for working with Word that have been compiled from various newsgroups. For those unfamiliar, newsgroups are a forum where users and developers can submit questions related to many technical subjects, such as Office applications. Questions are answered by users and other professionals. In this context, newsgroups are rich with information tailored to using and developing in your Office application of choice. The answers that make up these tips are the product of years of experience from super users and developers designated as Most Valuable Professionals (MVPs). More information on newsgroups can be found at the newsgroup help file.

This sample demonstrates using a Microsoft Visual Basic for Applications (VBA) procedure to programmatically add a control to a Word document and then adding a Click event handler for that control.

  1. Open a new document in Word.

  2. Press Alt+F11 to go to the Visual Basic Editor.

  3. Click Tools and then References and select the reference for Microsoft Visual Basic for Applications Extensibility.

  4. Insert a new module by clicking the Insert menu and then clicking Module. Add the following code:

    Sub AddButton()
        'Add a command button to a new document
        Dim doc As Word.Document
        Dim shp As Word.InlineShape
        Set doc = Documents.Add
        Set shp = doc.Content.InlineShapes.AddOLEControl(ClassType:="Forms.CommandButton.1")
        shp.OLEFormat.Object.Caption = "Click Here"
        'Add a procedure for the click event of the inlineshape
        '**Note: The click event resides in the This Document module
        Dim sCode As String
        sCode = "Private Sub " & shp.OLEFormat.Object.Name & "_Click()" & vbCrLf & _
                "   MsgBox ""You Clicked the CommandButton""" & vbCrLf & _
                "End Sub"
        doc.VBProject.VBComponents("ThisDocument").CodeModule.AddFromString sCode
    End Sub
  5. Run the procedure "AddButton."

  6. Once the code finishes running, you see a new CommandButton control on a new document. When you click the command button, its Click event fires, displaying a message.

You can display a message dialog box in order to provide information to a user before a document prints. For example, you display a message telling the user where to pick up the document after printing. To do this, create a macro named "FilePrint" that allows you to intercept the print command, add in your own dialog box, and then add the code that would print out the document as you normally would. Following is some sample code:

  1. On the Tools menu, point to Macro, and then click Visual Basic Editor.

  2. In the code window, type the following procedure:

    Sub FilePrint()
        MsgBox "I am printing " + ActiveDocument.Name
    End Sub

    Note that the macro must be named FilePrint.

  3. Close the Visual Basic Editor.

  4. Print the document by clicking the File menu and then clicking Print.

    The message dialog box is displayed.

  5. Click OK to close the dialog box and the document prints.

Do you ever wish that you could make running your macro as easy for your user as clicking a menu item? You can do just that by following this procedure:

  1. Click Tools, click Customize, click the Toolbars tab and then select the Shortcut menus item.

  2. Expand the drop-down list on that toolbar and locate the one to which you want to add the command.

  3. Next, move to the Commands tab of the Customize dialog box and select the Macros category and then click and drag the macro that you want onto the menu.

  4. Right-click the entry and customize as desired.

The following procedure demonstrates how to return the name and index number for a selected Shape object. This is useful if, for example, you need to access a particular shape object in code and need the name or index.

Sub ReturnShapeData()
    Dim ShapeName As String 'Name
    Dim i As Integer
    ShapeName = Selection.ShapeRange.Name
    For i = 1 To ActiveDocument.Shapes.Count
       If ActiveDocument.Shapes(i).Name = ShapeName Then
          MsgBox "Shape " & Chr(34) & ShapeName & Chr(34) & " is Shape " & i
       End If
       Exit For
    Next i
End Sub

The following code is used to change the date from the ##/##/#### format to a full date format. An example is changing 10/20/2004 to Wednesday 20 October 2004.

Sub ChangeDate()
   With Selection.find
      .Text = "[0-9]{2}/[0-9]{2}/[0-9]{4}"
      .MatchWildcards = True
      While .Execute
         Selection.Text = Format(Selection.Text, "DDDD d. MMMM YYYY")
         Selection.Collapse direction:=wdCollapseEnd
   End With
End Sub

The following procedure searches a specified directory and uses the file names found to populate a list dialog box.

Sub ListFilenames()
   Dim strMyFile As String
   Dim lngCounter As Long
   Dim DirectoryListArray() As String
   ReDim DirectoryListArray(1000)
   strMyFile = Dir$("c:\docs\*.*")
   Do While strMyFile <> ""
      DirectoryListArray(lngCounter) = strMyFile
      strMyFile = Dir$
      lngCounter = lngCounter + 1
   ReDim Preserve DirectoryListArray(lngCounter - 1)
   Frm.lstNormals.List = DirectoryListArray
End Sub

The following sample checks for the existence of a file in a directory. If the Dir function returns a zero-length string, the file was not found, and a message box is displayed. If the Dir function finds the file, an appropriate message box is displayed.

Sub DoesFileExist(SearchFile As String)
   Dim FileInQuestion As String
    FileInQuestion = Dir(SearchFile)
   If FileInQuestion = "" Then
      MsgBox "No such file!"
      MsgBox "File exists!"
   End If
End Sub

In Word, you can create a custom dialog box to prompt a user for information by using text boxes. Typically, when you type text in the text box, the text appears as you type. However, you can use a property of a Visual Basic Edition UserForm to create the effect of a hidden or masked text box. This can be useful for creating a password dialog box, where you do not want the text that is typed in a text box to be visible. To test this, do the following:

To create a Dialog Box

  1. Start Word.

  2. Press Alt+F11 to start the Visual Basic Editor.

  3. In the Insert menu, click User Form.

  4. Using the Controls toolbox, add a text box and a command button to your user form.

  5. On the Properties sheet, in the Object list, click TextBox1.

  6. On the Alphabetic tab, click PasswordChar.

  7. Type an asterisk ( * ).

  8. On the Properties sheet, in the Object list, click UserForm1.

  9. Click the user form to select it.

  10. On the Run menu, click Run User Form.

When you type letters, the asterisk appears instead.

Code Sample to Retrieve the Text

To retrieve the text string written to the text box, you can use the following sample code:

  1. Double-click CommandButton1 on your user form.

  2. Type the following code:

    Private Sub CommandButton1_Click()
        MsgBox Me.TextBox1
    End Sub
  3. Click Save to save your project.

  4. On the Run menu, click Run Sub/User Form.

  5. Type a word in the text box, and then click the Command button. The text that you typed appears in the message box.

The following procedures remove or reset document protection:

Sub ProtectIt(ProtectType)
    If ProtectType <> wdNoProtection Then
        If ActiveDocument.ProtectionType = wdNoProtection Then
            ActiveDocument.Protect Type:=ProtectType, NoReset:=True,
        End If
    End If
End Sub

Function UnprotectIt()
    wasLocked = ActiveDocument.ProtectionType
    If ActiveDocument.ProtectionType <> wdNoProtection Then
        ActiveDocument.Unprotect "My_Password"
    End If
    UnprotectIt = wasLocked
End Function

To use it in a code segment, try this:

' First unprotect the document.
ProType = UnprotectIt()
' Here goes the code to be done in the unprotected document
' then lock it back up.
ProtectIt ProType

This article presents a number of tips and VBA code for use in Word. By using these procedures and modifying them for your own use, you can make your own applications more robust and provide more options to your users.