Automating Repetitive Tasks in FrontPage 2003

 

Lisa Wollin
Microsoft Corporation

June 2004

Applies to:
    Microsoft Office FrontPage 2003
    Microsoft FrontPage 2002
    Microsoft FrontPage 2000

Summary:   Learn the basics of creating macros in Microsoft Office FrontPage 2003 to automate repetitive tasks. (33 printed pages)

Contents

Introduction
Understanding the Visual Basic Editor
Understanding Visual Basic
Understanding the FrontPage Object Models
Sample Macros
Getting Started

Introduction

Do you ever find yourself performing the same steps over and over again? Perhaps you publish the same Web site to several locations and find yourself repeatedly typing the Web addresses into the Publish dialog box every time you need to publish the site. Or perhaps you want to add a reference to an external style sheet to every page in your Web site and don't want to open every page to paste the necessary HTML. Macros can help.

Macros allow you to automate repetitive tasks. If you've worked with other Microsoft® Office applications, you've probably worked with macros. In fact, several Office applications have a macro recorder that you can use to create macros for those applications. Although you can't record macros in FrontPage, you can still create macros to automate your tasks, and you can create some powerful macros. With a little instruction, you can begin to develop your own collection of macros.

Note   Macros in FrontPage are useful for design-time tasks and are available only within the FrontPage application. They do not work when pages created with FrontPage are displayed in a browser.

Understanding the Visual Basic Editor

As with other Office applications, you create macros for FrontPage in the Microsoft Visual Basic® Editor using the Visual Basic for Applications (VBA) programming language. If you work with other programming languages, such as JavaScript, you already have the skill to create macros for FrontPage. But even if you aren't an experienced programmer, you can still create some great macros.

Note   A thorough discussion of Visual Basic, Visual Basic for Applications, and the Visual Basic Editor is beyond the scope of this article. Instead, this article is designed to give a general overview of how to create macros by using the FrontPage object model. For more information, about Visual Basic for Applications in Office see the Microsoft Office 2000/Visual Basic Programmer's Guide. There are also several books available that you can use for more information, including Microsoft Office FrontPage 2003 Inside Out, published by Microsoft Press, and VBA Developer's Handbook, written by Ken Getz and Mike Gilbert and published by Sybex.

To get started, you need to open the Visual Basic Editor. You can access the Visual Basic Editor from the Tools menu by pointing to Macro and clicking Visual Basic Editor. (Alternatively, you can press ALT+F11.)

When the Visual Basic Editor opens, it looks something like the screen shot in Figure 1.

Click here to see larger image

Figure 1. Visual Basic Editor (Click picture to view larger image)

Notice the three main areas of the Visual Basic Editor screen: the Project Explorer, the Properties window, and the Code window.

Using the Project Explorer

The Project Explorer, as shown in Figure 1, contains all the code and class modules and custom user forms that are part of a VBA project.

  • A code module is a set of declarations followed by procedures.
  • A class module defines an object with properties, methods, and sometimes events. A class module acts as a template from which you can create objects in your project.
  • A user form is a custom dialog box to which you can add custom controls, such as command buttons, text boxes, and lists.

When you first start the Visual Basic Editor, you generally see a Modules folder that contains a code module named "Module1," as shown in Figure 2. As with other Office applications and with Microsoft Visual Basic 6.0, you can add additional code modules, classes, and forms to your macro project. When you add additional code modules, class modules, and forms, you will see these listed in the Project Explorer.

Figure 2. Project Explorer

Unlike other Microsoft Office applications, which are stored with the document or project, FrontPage macros are stored by user. What this means is that each FrontPage user on a computer has his or her own set of FrontPage macros that is available. All macros in FrontPage are stored in a file named "Microsoft FrontPage.fpm" in %userprofile%\Application Data\Microsoft\FrontPage\Macros, where %userprofile% is the Document and Settings folder for the current Windows user.

You can share your macros with other users by exporting the modules and user forms. To do this, you export the file on your computer, and then the person to whom you send it imports it. To export a file, select in the Project Explorer the module or form that you want to share; then on the File menu, click Export File. To import a file, on the File menu click Import File; navigate to the file that you want to import and click Open.

Alternatively, you can also send the Microsoft FrontPage.fpm file. In this case, those to whom you send it open the file as a project. To do this, on the File menu click Open Project; change Files of type to All Files (*.*); then locate the file and click Open. When you do this, you see a new project listed in the Project Explorer.

Using the Properties Window

The Properties window allows you to make changes quickly to the properties of modules, forms, and form controls. You can change the names of the code modules, class modules, and user forms as well as display and change properties for user forms and form controls.

Figure 3 shows the properties for the Module1 code module. You will see one property, Name, for which you can specify a value. In this case, the name of the code module is "Module1." By typing a value into the text area next to the Name property, you can specify a different name for the module.

Figure 3. Properties window

Using the Code Window

Finally, the Code window, shown in Figure 4, is where you write your macros.

Click here to see larger image

Figure 4. Visual Basic Editor Code Window (Click picture to view larger image)

You may notice one difference in this figure from what you see in your own Code window: the text "Option Explicit" at the top of the Code window in the image. Option Explicit simply indicates to the Visual Basic Editor that all variables must be declared.

If you have worked with other programming languages, you know that not all programming languages require that you declare variables. If you have never programmed before, don't worry. You will learn all about declaring variables later in this article. For now, to ensure that the code you write later requires variable declaration, type "Option Explicit" at the top of the Code window.

Requiring variable declaration for your entire VBA project is also a good idea. This means that when you add modules and forms, you do not need to remember to type "Option Explicit" at the top of the Code window.

To require variable declaration for your entire VBA project

  1. On the Tools menu, click Options.
  2. In the Options dialog box, click the Editors tab.
  3. Select the Require Variable Declaration check box.
  4. Click OK.

Understanding Visual Basic

Now that you have familiarized yourself with the Visual Basic Editor, it is time to learn about writing macro code. Visual Basic for Applications, or VBA, is a subset of Visual Basic. Visual Basic is an event-driven, object-oriented programming language. This means that you can create custom objects and respond to user events with Visual Basic code. As a child of Visual Basic, VBA also allows you to create custom classes and respond to events.

Working with Subroutines

When you write a macro, you write a procedure that performs the steps you need to complete a task. Subroutines are a type of procedure and are the type of procedure that you will use most to create macros. All subroutines begin with "Sub" and end with "End Sub." The following example shows a custom subroutine named "MySubroutine."

Sub MySubroutine()

End Sub

In VBA, you can simply type "sub MySubroutine" and press ENTER, and the Visual Basic Editor will enter the parentheses and "End Sub" for you. Visual Basic, and thus VBA, is not case sensitive, so you can type "sub" or "Sub" without causing errors in your code.

Working with Functions

Subroutines are only one type of procedure. Subroutines perform an action but don't return a value. To return a value from a procedure you need a function. In VBA, a function starts with "Function" and ends with "End Function". With a function, you also generally specify the type of the return value. The following example shows a custom function named "MyFunction" that returns a String data type. Note how the example uses the As keyword to specify the String data type.

Function MyFunction() As String

End Function

When you define a function, you generally return a value from the function. To do this, you assign the return value to the function name. For example, the following example shows the MyFunction function assigning the String "This is a string." to the MyFunction function name. Therefore, the function name acts almost as a variable. (You will learn more about variables in the next section.) This causes the procedure that called the function to receive the String.

Function MyFunction() As String
    MyFunction = "This is a string."
End Function

Declaring Variables

As mentioned earlier, you should always declare your variables before using them. In some programming languages, such as JavaScript, you can assign a value to a variable without specifying the data type. However, in strongly typed languages, such as Visual Basic, declaring a variable as a specific data type tells the computer to reserve just that amount of space in memory to contain the value of the variable. This is important because if your macro contains many variables, you could slow the performance of the macro by not specifying a type for each variable.

When you strongly type an object variable, the Visual Basic Editor provides IntelliSense® technology, which lists the properties and methods that apply to that object. In addition, objects require strongly typed variables to access events.

In Visual Basic, you declare variables by using the Dim keyword and you specify the data type by using the As keyword. There are data types for all the various types of data that you can assign to a variable. For words and letters, you use the String data type. For numbers, you can use Integer, Double, Single, and Long, among others.

In addition, Visual Basic provides two generic types that you can use when declaring variables: Object and Variant. These types are useful if you are not sure of the exact data type for a variable. However, you should use these types rarely and should consider them only for special circumstances because the memory allocation for these generic data types is greater than for other data types.

For more information, see Declaring Variables in the Office Visual Basic Programmers Guide and Data Types in the Visual Basic 6.0 Programmer's Guide.

The following example uses the MyFunction function shown earlier and declares a String variable named strTemp, assigns a value to the variable, and then returns the value of the variable by assigning it to the MyFunction function name.

Function MyFunction() As String

    Dim strTemp As String
    strTemp = "This is a string."
    MyFunction = strTemp
End Function

Notice the variable in the previous code example prefaces the variable name with "str". This prefix identifies the data type of the variable, which in this case is a String. This naming convention is a modified Hungarian notation. For more information, see Naming Variables and Constants.

Understanding Constants

Constants are similar to variables except that unlike a variable, whose value can change, the value of a constant remains the same. When you declare a constant, you use the Const keyword and immediately assign a value to the constant. The following example declares a constant named CONSTANT.

Const CONSTANT As String = "This is a constant."

Constants are most useful when you are working with a value that will never change, such as the value of pi. Note that the constant declared in the preceding example is specified in capital letters. For more information, see Constants in the Visual Basic 6.0 Programmer's Guide.

Working with Parameters

Both subroutines and functions can have parameters. Parameters allow you to pass values into a procedure. Generally, these values either affect the results of the procedure or are needed in processing the procedure code. The following example shows a subroutine that takes two parameters: one Integer and one String.

Sub MySubroutineWithParameters(intI As Integer, str1 As String)

End Sub

Inside the procedure, you would use the parameter the same as you would use a declared variable.

Creating Optional Parameters

Visual Basic allows you to create optional parameters. You can do this simply by prefacing the parameter name with the Optional keyword. The following example adds two optional parameters to the MySubroutineWithParameters procedure shown previously.

Sub MySubroutineWithParameters(intI As Integer, str1 As String, Optional blnB
 As Boolean, Optional str2 As String)

End Sub

Note   You can list optional parameters only after the required parameters. Doing otherwise produces a run-time error.

Calling Another Procedure

Ideally, each macro that you create would perform a single action; however, sometimes you might want to combine several unique actions into a single macro. In this case, you can create a procedure that calls one or more other procedures. To do this, you can use the Call statement or just specify the name of the procedure that you want your code to run. For example, the following example uses the Call statement to call a procedure named AnotherSubroutine from the MySubroutine procedure.

Sub MySubroutine()
    Call AnotherSubroutine

End Sub

You could also omit the Call statement and write the preceding code as shown in the following example. In both cases, the returned value is discarded.

Sub MySubroutine()
    AnotherSubroutine
End Sub

However, if you are calling a function, you would generally want to assign to a variable the value that the function returns. In the following example, the MySubroutine procedure assigns the value of the MyFunction procedure to a variable named strTempString and then displays the string in a message box.

Sub MySubroutine()
    Dim strTempString As String
    strTempString = MyFunction
    MsgBox strTempString
End Sub

Function MyFunction() As String
    Dim strTemp As String
    strTemp = "This is a string."
    MyFunction = strTemp
End Function

Calling a Procedure with Parameters

There may be times when you want to call a procedure that has parameters. When you call a procedure that has parameters, the parameter values are called arguments. When you pass arguments for parameters, you must separate the argument values with commas. In the following example, the MySubroutine procedure calls the MySubroutineWithParameters procedure and passes two arguments. Notice the comma between the argument for the first parameter, "3", and the argument for the second parameter, "This is a string."

Sub MySubroutine()
    MySubroutineWithParameters 3, "This is a string."
End Sub

Alternatively, you could also write this example as shown in the following code fragment. Notice that, in this case, the code uses the Call keyword and puts parentheses around the arguments.

Sub MySubroutine()
    Call MySubroutineWithParameters(3, "This is a string.")
End Sub

The parentheses are required whenever you use the Call keyword or assign the value to a variable. As shown in the following example, the MyFunctionWithParameters procedure returns a String. Because the code assigns the returned value to a variable, the parentheses around the arguments are required.

Sub MySubroutine()
    Dim strTempString As String
    strTempString = MyFunctionWithParameters(3, "This is a string.")
End Sub

Note   If you exclude the parentheses when they are required or include them when they are not required, the Visual Basic Editor displays an error message.

Using Named Arguments

As explained earlier, Visual Basic allows you to create procedures that have optional parameters. If you want to omit an argument for an optional parameter, you can simply not include it. However, if you want to provide an argument for one or two optional parameters but not for others, you need to ensure that the argument that you pass is assigned to the correct parameter. For example, perhaps you want to call a procedure that has two required parameters and two optional parameters, and you want to pass a value for only the second optional parameter. If you didn't specify which parameter receives the argument, the procedure could either produce faulty results or return a run-time error.

To specify which parameter receives which argument, you can insert empty values by using additional commas, as shown in the following example, or you can use named arguments.

As you can see in the following code, the MySubroutine calls the MySubroutineWithParameter procedure and omits the first optional parameter but provides an argument for the second optional parameter. Notice in this example that there is a space and a comma for the omitted argument.

Sub MySubroutine()
    Call MySubroutineWithParameters(3, "This is a string.", , "Another string.")
End Sub

To eliminate code filled with spaces and commas, you can use named arguments. When you use named arguments, you preface the argument value with the parameter name and a colon (:) and equal (=) sign. The following example shows MySubroutine procedure calling the MySubroutineWithParameters procedure with named parameters. Notice that, unlike the previous example, this example doesn't have an empty space for the third parameter.

Sub MySubroutine()
    Call MySubroutineWithParameters(intI:=3, str1:="This is a string.", str2:="Another string.")
End Sub

When you are writing code, the Visual Basic Editor displays the signature for the method, property, or function that you are using. As you can see in Figure 5, this signature includes the name and expected data type for each parameter, so you don't need to memorize all the parameter names to use named arguments.

Figure 5. Example of signature display

Terminating a Line of Code

Many programming languages use a special character to terminate a line of code. For example, in JavaScript, you end each line with a semicolon. This indicates to the browser that the program statement has ended and means that the code for a single statement can run onto multiple lines and still be included in the same statement.

In Visual Basic, each line of code is a separate statement, and the line break at the end of the line determines when a statement ends. However, for readability, you may want to split a long line of code into separate lines. To do this, you end the line with a space and an underline character. This tells the Visual Basic compiler to continue the statement on the following line. The following example shows a subroutine that places the procedure declaration line onto multiple lines.

Sub SampleSubroutineThatHasALotOfParameters(strSample1 As String, _
        strSample2 As String, blnIsTrue As Boolean, blnIsClean As Boolean, _
        intCount As Integer, intTotal As Integer)

End Sub

Running and Debugging Code

As you are writing macros, it is a good idea to test the code to ensure that it functions as expected and without errors. To do this you can run code by positioning the insertion point inside the code that you want to test and pressing F5. To demonstrate, copy the following code into the Visual Basic Editor Code window, position the insertion point in the MySubroutine procedure, and press F5. You immediately see the message box displayed.

Sub MySubroutine()
    MsgBox ShowMessage("This is a string.")
End Sub

Function ShowMessage(Message As String) As String
    Dim strTemp As String
    strTemp = Message
    ShowMessage = strTemp
End Function

You can also step through the code line by line by pressing F8. This is especially useful if you need to fix a problem, or bug, in the code. To demonstrate, position the insertion point in the MySubroutine procedure again, and this time press F8. What you see is a highlighted line of code. (By default, the highlighting is yellow.) This is the line of code that executes the next time you press F8. As you press F8, notice that the highlighted section moves through the code until finally the code ends.

Note   You cannot start executing code from within procedures that have one or more parameters. In this case, you need a test procedure that calls the procedure and provides the necessary arguments. The MySubroutine procedure in the preceding example is a test procedure that calls the ShowMessage function.

Using Control Structures

In Visual Basic, you can write code that will execute only in certain situations, that will execute a specified number of times, or that will execute until another condition occurs. While Visual Basic has many different types of control structures, the ones you will encounter most when writing macros are If statements, For loops, and Do loops. For more information about these and other control structures, see Introduction to Control Structures.

If Statements

If statements allow you to specify conditions that determine whether code will run. In all cases, the specified condition must evaluate to True before the code within it will run. The syntax for an If statement is as follows:

If Condition = value Then
...Insert conditional code here.
End If

Note   The operator, shown in the previous syntax as an equal sign (=), can be any operator that Visual Basic allows. For more information on using operators, see Operator Summary in the Visual Basic Programmer's Guide.

For Boolean values, if you don't specify a value, the condition will evaluate to True. For example, you might want to perform an action if a certain page is open. In the following example, the If statement determines whether a page is open. If the page is open, the code within the If statement will run.

If Page.IsOpened Then
    'Code to run.
End If

Note   You could also write the If statement in the previous example as Page.IsOpened = True.

If you want to show inequality, you can use the inequality operator (<>) or the Not keyword. The following example shows three If statements, one using the Not keyword, one using the inequality operator, and one evaluating whether the value is equal to False. Each statement evaluates to True if a page is not open.

If Not Page.IsOpened Then
    'Code to run.
End If

If Page.IsOpened <> True Then
    'Code to run.
End If

If Page.IsOpened = False Then
    'Code to run.
End If

You can even create multiple and cascading If statements by using the Else or ElseIf keywords. The following example shows an If statement that determines whether a variable contains a certain value and then uses the ElseIf keyword to check to determine whether the variable contains another value. If neither the If nor ElseIf statements execute, the code under the Else statement runs.

Sub ExampleSubroutine(intI As Integer, str1 As String)
    If intI = 1 Then
        'Execute this code.
    ElseIf intI = 2 Then
        'Execute this code.
    Else
        'Execute this code if all other conditions fail.
    End If
End Sub

In this case, if the parameter intI equals 1, the first block of code runs. If not, the code checks for the second condition, intI equals 2. If the second condition is also false, the code in the final Else statement runs.

Note   You can also use a Select Case statement instead of cascading If statements. For more information, see Decision Structures.

For Loops

For loops allow you to execute code a specified number of times or to loop through the objects in a collection. (For more information on collections, see Understanding Objects, Properties, and Methods later in this article.) To loop through code a specified number of times, you use the following syntax.

For TempVariable = 1 To SpecifiedNumber
    'Execute code.
Next

The following example concatenates the specified string the number of times specified by the Count parameter. The For loop increments automatically; when the temporary variable i is equal to Count, the loop terminates and returns the results to the calling routine.

Function ConcatenateString(Count As Integer, Message As String) As String
    Dim intI As Integer
    Dim strMessage As String

    For intI = 1 To Count
        strMessage = strMessage + Message
    Next

    ConcatenateString = strMessage
End Function

Sub CallConcatenateString()
    MsgBox ConcatenateString(5, "Test string.")
End Sub

When you run the preceding code, the message box shown in Figure 6 is displayed.

Figure 6. Test string message box

You can also loop through objects in a collection. In this case, you use a For Each loop. The syntax for a For Each loop is as follows:

For Each object In collection
    'Execute code.
Next

To demonstrate, the following example loops through all the Web sites that are open in FrontPage and displays a message box containing the file path for each Web site.

Sub LoopThroughWebSites()
    Dim objWeb As WebEx

    For Each objWeb In FrontPage.Webs
        MsgBox objWeb.Url
    Next
End Sub

Note   This article describes working with objects and collections in more detail in the section Understanding the FrontPage Object Models.

Do Loops

Do loops can take two basic forms: Do While and Do Until. A Do While loop executes as long as a set condition is true. The syntax for a Do While loop is as follows:

Do
    'Code to execute as long as the condition remains the same.
Loop While condition

The following example demonstrates using the Do While loop. This code executes as long as the value of the counter is less than 25.

Sub DoWhileLoop()
    Dim intCount As Integer

    Do
        Debug.Print intCount
        intCount = intCount + 1
    Loop While intCount < 25
End Sub

Note   The preceding example uses the Print method for the Debug object. You can use Debug.Print to write text and numbers to the Immediate window in the Visual Basic Editor. To show the Immediate window, click Immediate Window on the View menu (or press CTRL+G). For more information, see Printing Information in the Immediate Window.

Notice that code within the loop increments the counter variable. This means that the condition will eventually be false and the loop will stop. This is important because without the code that increments the counter, you create an infinite loop, or code that never stops. Because this would cause FrontPage to freeze, you should be careful when writing Do loops to ensure that the condition will eventually change, thus terminating the code.

By contrast, a Do Until loop executes until a set condition becomes true. The syntax for the Do Until loop is as follows.

Do
    'Code to execute until the condition changes.
Loop Until condition

For example, the following code executes the Do Until loop until the value of the counter is greater than 25.

Sub DoUntilLoop()
    Dim intCount As Integer
    
    Do
        Debug.Print intCount
        intCount = intCount + 1
    Loop Until intCount > 25
End Sub

Again, notice that code within the loop increments the counter variable. This means that the condition will eventually be true and the loop will stop.

With the preceding syntax, a Do loop will always execute at least once because the condition isn't checked until after the code executes, at which time the code may execute again. However, you might want code to execute only if it meets a specified condition. In this case, you can put the condition at the beginning of the loop. The following syntaxes for Do While and Do Until loops will cause the code to be skipped if the condition isn't met.

Do While condition
    'Code to execute as long as the condition remains the same.
Loop

Do Until condition
    'Code to execute until the condition changes.
Loop

Handling Errors

Sometimes the code you write raises errors if certain conditions aren't met. For example, in FrontPage 2000 and FrontPage 2002, the active view mode must be Normal when modifying the HTML code in a Web page. If the view mode is other than Normal, you will receive an "Access Denied" error.

Note   Unlike earlier versions of FrontPage, in which you could not edit the HTML programmatically when the active view in FrontPage was something other than Normal or Design view, FrontPage 2003 allows you to make changes to the HTML even when the pages are displayed in Code view or Split view. However, extensive changes to the HTML in a page may cause an error. In these cases, you can switch to Design view and save the page, or you can use the parseCodeChanges method.

You can handle errors in several ways. You can plan and code for the possible error. For example, if the view mode is not set to Normal, as in the case described earlier, you can use the following code to check whether the active view is Normal view and switch to Normal view if it is not.

If ActivePageWindow.ViewMode <> fpPageViewNormal Then _
    ActivePageWindow.ViewMode = fpPageViewNormal

However, sometimes you are unable to plan for an error, such as when you don't know all the conditions under which code will run. In this case, you can use traditional Visual Basic error handling. The following example shows a simple error handler in a subroutine.

Sub SampleErrorHandler()
    On Error GoTo ErrorHandler

    '...insert code here.

ExitSubroutine:
    Exit Sub

ErrorHandler:
    MsgBox Err.Number & vbCrLf & Err.Description
    GoTo ExitSubroutine

End Sub

Notice that the preceding example uses the On Error and GoTo keywords. The On Error statement also specifies the name of the error handler to skip to if an error occurs. In this case, the name of the line is ErrorHandler. A line lower in the code is labeled "ErrorHandler" and is followed by a colon. This is a line label; it marks the code that will run if an error occurs.

In addition, good programming principles state that all subroutines should have a single point of exit. To that end, you can also see the line label "ExitSubroutine"; the code that follows provides the exit point for the subroutine. In addition, the code uses the GoTo keyword to transfer execution to the ExitSubroutine line label so that the ErrorHandler code can use the same exit point.

The following example attempts to assign a String to an Integer variable. This action raises a Type mismatch error. If you copy this code to the Visual Basic Editor and step through the code (F8), you will see the general flow.

Sub SampleErrorHandler()
    On Error GoTo ErrorHandler

    Dim intCount As Integer

    intCount = "String data type."

ExitSubroutine:
    Exit Sub

ErrorHandler:
    MsgBox Err.Number & vbCrLf & Err.Description
    GoTo ExitSubroutine

End Sub

For more information on handling errors in Visual Basic, see Debugging Your Code and Handling Errors.

Understanding Objects, Properties, and Methods

Objects are the fundamental building blocks of Visual Basic; nearly everything you do in Visual Basic involves working with objects. Most elements of FrontPage&#151;Web sites, Web files, HTML elements, navigation, and so on&#151;can be represented by objects in the Visual Basic for Applications object models.

What Are Objects and Collections?

An object represents an element of FrontPage, such as a Web site, a document, or an HTML element. A collection is an object that contains other objects, usually of the same type; for example, all the files in a Web site, represented by WebFile objects, are contained in WebEx objects, which in turn are contained in the Webs collection. Using the associated properties and methods, you can modify a single object or an entire collection of objects.

What Is a Property?

A property is an attribute of an object or an aspect of its behavior. For example, the properties of a Web page include its filename, its HTML contents, and its title, as well as whether the document has been changed since it was last open. To set the characteristics of an object, you set the values of its properties.

To set the value of a property, follow the reference to an object with a period, the property name, an equal sign, and the new property value. The following example sets the title for the currently open Web page.

Sub TrackChanges()
    ActiveDocument.Title = "Quarterly Sales Report"
End Sub

Some properties are read-only; their values cannot be changed in your code. You can use read-only properties to return information about an object. The following example displays the name of the active document.

Sub GetPageName()
    Dim strPageName As String
    strPageName = ActiveDocument.nameProp
    MsgBox strPageName
End Sub

In this example, the code assigns the nameProp property of the active page to the variable strPageName, and then displays the value of the String in a message box.

What Is a Method?

A method is an action that an object can perform or that can be performed against an object. For example, you can use the Open method for the WebFile object to open a Web page. Methods can have arguments that qualify how the action is performed. The following example uses the writeFile method to save the current page to a specified path.

Sub MoveFile()
    ActiveDocument.writeFile Path:="c:\temp\tempsite\newpage.htm"
End Sub

In most cases, methods are actions and properties are qualities. Using a method causes something to happen to an object, while using a property returns information about the object or causes a quality of the object to change.

Accessing Objects

Individual objects are generally contained within collections. For example, the Webs collection contains individual WebEx objects. One WebEx object represents one Web site opened in FrontPage, so the Webs collection represents all the Web sites opened in FrontPage. You use the Webs property to return the Webs collection.

After you access the collection, you can return a single WebEx object by using an index value in parentheses. The index value can be either a number, which represents the position of a WebEx object within the Webs collection, or a name, which is a String that represents the name of the Web site.

The following example uses the Webs property to access the Webs collection. The index number is used to return the first open Web site in the Webs collection. The Close method is then applied to the WebEx object to close the Web site and remove it from the Webs collection.

Sub CloseActiveWebSite()
    Application.Webs(0).Close
End Sub

You might want to use a variable to store the contents of an object. This kind of variable is called an object variable. In this case, you must use the Set keyword to set the contents of the variable equal to the object. The following example creates an object variable for the active Web site and then displays the file path for the Web site.

Sub CreateObjectVariable()
    Dim objWebSite As WebEx
    Set objWebSite = ActiveWeb
    MsgBox objWebSite.Url
End Sub

To return an object that is farther down in the FrontPage object hierarchy, you must "drill down" to it by using properties and methods to return objects. The following example creates an object variable that contains the contents of the first TABLE element in the active Web page and changes the background color for the table to light gray. This example uses the all property to return a collection of all the HTML elements in the page, and then uses the tags method to filter the elements to include only those of the specified tag, which in this case is the TABLE element. Finally, it uses the Item method to include only the first TABLE element in the collection of TABLE elements.

Note   All FrontPage collections are zero based, so to return the first item in a collection you specify it as "0".

Sub GetTableObject()
    Dim objTable As FPHTMLTable

    Set objTable = ActiveDocument.all.tags("table").Item(0)

    objTable.bgColor = "#EEEEEE"
End Sub

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. For more information about the object hierarchy for an object model, you can use the Object Browser in the Visual Basic Editor, which you can access by clicking Object Browser on the View menu or by pressing F2.

Getting Help on Objects, Methods, and Properties

Until you become familiar with the FrontPage object model, you can use a few tools to help you to understand the hierarchy and access the objects that you need.

  • Auto List Members  When you type a period (.) after an object in the Visual Basic Editor, a list of available properties and methods is displayed. For example, if you type Application and a period, a drop-down list of methods and properties of the Application object is displayed. This is also called IntelliSense technology.

    Note   In some cases, you do not get a list of applicable members. In these cases, you must resort to the Object Browser and the VBA online help. In addition, IntelliSense works only for strongly typed object variables. Therefore, if you declare a variable as Object or Variant, you do not see this behavior.

  • Object Browser  The Object Browser in the Visual Basic Editor displays the members (properties, methods, and events) of the FrontPage object models and their related objects.

  • Online Help  You can also use the VBA online help to discover which properties and methods you can use with an object. Each object topic in the online help includes a See Also link that displays a list of properties and methods for the object. Press F1 in the Object Browser or select an object, method, property, or event within a module to display the appropriate help topic.

Understanding the FrontPage Object Models

Now that you know a little more about how to write Visual Basic code, you can create simple procedures in the Visual Basic Editor. However, to create macros that automate commonly performed tasks in FrontPage, you need to use the FrontPage object models. FrontPage has three distinct object models: the Web object model, the Page object model, and the Application object model. These object models provide a rich set of programmable interfaces with which to manipulate documents, files, folders, and the FrontPage application window.

**Note   **Not all objects, properties, and methods are available in all versions of FrontPage. For example, the WebEx object is not available in FrontPage 2000, but the Web object is available. All objects and members shown in this article are available in FrontPage 2003. If sample code does not run on your version of FrontPage, see the Object Browser for a list of objects and members. For more information, see Using the Object Browser.

Web Object Model

The Web object model provides access to many of the FrontPage Web-level features. For example, using the Web object model, you can create, open, and delete Web sites; add new files and folders to a Web site; and apply themes to some or all files in a Web site. The following example creates a new Web site at C:\Temp\TempSite and populates it with three pages.

Sub CreateNewWebSite()
    Dim objWeb As WebEx

    Set objWeb = Webs.Add("C:\Temp\TempSite")
    objWeb.AllFiles.Add "C:\Temp\TempSite\Page1.htm"
    objWeb.AllFiles.Add "C:\Temp\TempSite\Page2.htm"
    objWeb.AllFiles.Add "C:\Temp\TempSite\Page3.htm"
End Sub

To see this code in action, copy it into the Visual Basic Editor Code window and run it by pressing F5. Another session of FrontPage starts and is pre-populated with three pages: Page1.htm, Page2.htm, and Page3.htm.

Note   The AllFiles property was not available in versions prior to FrontPage 2002, so this code will run only in FrontPage 2002 and FrontPage 2003.

Page Object Model

The Page object model is a superset of the Microsoft Internet Explorer Dynamic HTML object model. If you have used Dynamic HTML scripting, you will find the FrontPage Page object model very familiar. The FrontPage Page object model incorporates most of the design-time objects, methods, properties, and events of the Dynamic HTML object model. However, the run-time components do not make sense in the design-time FrontPage environment, so these are disabled. In addition, FrontPage has a number of objects to support FrontPage-specific features.

You use the Page object model to access the HTML in a page. For example, if you want to change the title of a Web page, you could use the following code.

Sub ChangeTitleForPage()
    ActiveDocument.Title = "Insert New Title Here"
End Sub

However, this code assumes that a page is open in FrontPage. You can test for this condition by ensuring that the ActiveDocument property contains a value, or in this case is not null, or nothing. The following example rewrites the previous example to test for this condition.

Sub ChangeTitleForPage()
    If Not ActiveDocument Is Nothing Then
        ActiveDocument.Title = "Insert New Title Here."
    End If
End Sub

In this example, the code that sets the page title does not run if no documents are open in FrontPage, thus eliminating any errors that may occur. The line If Not ActiveDocument is Nothing indicates that the code should run only if ActiveDocument is not null. You could also write this line as If ActiveDocument Is Nothing = False.

Application Object Model

The Application object model is the access point for everything in the Microsoft Office object model. The Application object model is composed of objects that implement operating system or global Office objects and collections. It contains the COMAddIns collection, the AnswerWizard object, the System object, and the CommandBars collection. You also access application-wide events from the Application object.

Sample Macros

The following sections provide a selection of sample macros designed to perform specific tasks. These code examples can help you get started developing your own macros. You can copy and reuse these macros or modify them as you need. Note that not all of the code samples provide work with all versions of FrontPage. You can determine whether your version of FrontPage works with a specified code sample by reading the list of versions at the beginning of each code sample section.

Code Samples

  • Adding HTML to a Page
  • Determining Whether a Web Page Is Open
  • Finding and Replacing Text
  • Inserting an Interactive Button
  • Opening and Editing Files
  • Publishing a Web Site to Multiple Locations
  • Saving a Page
  • Selecting Files from the File Open Dialog Box

Adding HTML to a Page

In FrontPage 2003, FrontPage 2002, and FrontPage 2000, this function adds any HTML content to a specified document, either appending to or replacing the document. It does this by creating an IHTMLTxtRange object from the body element of the FPHTMLDocument object. If the argument for the blnClearPage parameter is True, the entire contents between the opening and closing <body> tags is replaced; otherwise, the HTML is appended to the bottom of the current content, before the closing <body> tag.

The objects used in this example are as follows:

  • FPHTMLDocument
  • IHTMLTxtRange
  • FPHTMLBody

Adding HTML to a Page Example

Public Function AddHTMLToPage(objPage As FPHTMLDocument, _
        strHTMLtext As String, blnClearPage As Boolean) As Boolean

    Dim objRange As IHTMLTxtRange
    Dim objBody As FPHTMLBody

    On Error GoTo ErrorHandler

    If blnClearPage Then
        Set objRange = objPage.all.tags("BODY").Item(0).createTextRange
        ' clear out the current document

        If blnClearPage Then
            Call objRange.pasteHTML("")
        End If

        objRange.collapse False
        Set objRange = Nothing
    End If

    Set objBody = objPage.body
    objBody.innerHTML = objBody.innerHTML & strHTMLtext & vbCrLf

    AddHTMLToPage = True

ExitFunction:
    Exit Function

ErrorHandler:
    'Could not insert HTML.
    AddHTMLToPage = False
    GoTo ExitFunction

End Function


'Use the following subroutine to call the preceding function.
Sub CallAddHTMLToPage()

    Dim strHTMLString As String
    strHTMLString = "<P><B><I>BLAH</I></B></P>" + vbCrLf

    Call AddHTMLToPage(ActiveDocument, strHTMLString, True) 
End Sub

Determining Whether a Web Page Is Open

In FrontPage 2003 and FrontPage 2002, these two examples determine whether a particular document is open. After they determine that the specified document is open, they perform an action on the file. Both examples work similarly; however, the first example uses the WebFiles collection to specify the file directly, while the second example loops through all the files in the active Web site to determine whether the specified one is open.

Another notable difference between the two examples is that the first function simply returns a Boolean to indicate whether the file is open and the calling subroutine then displays a message indicating whether the file is open or closed. However, in the second example, the function performs the action against the file and then returns a Boolean to indicate whether the function performed the action. In this case, if the file is currently opened, the CheckForOpenFile function below returns False.

The objects used in this example are as follows:

  • WebEx
  • WebFile
  • WebFiles

Determining Whether a Web Page Is Open Example 1

Public Function IsPageOpen(strDocumentURL As String) As Boolean

    On Error GoTo PageDoesntExist

    IsPageOpen = ActiveWeb.AllFiles.Item(strDocumentURL).IsOpen

ExitFunction:
    Exit Function

PageDoesntExist:
    MsgBox "Page doesn't exist."
    IsPageOpen = False
End Function


'Use the following subroutine to call the preceding function.
Sub CallIsPageOpen()
    If IsPageOpen(strDocumentURL:="default.htm") Then
        MsgBox "Open"
    Else
        MsgBox "Not Open"
    End If
End Sub

Determining Whether a Web Page Is Open Example 2

Public Function CheckForOpenFile(strFileToOpen As String) As Boolean
    Dim objFile As WebFile
    Dim blnFileExists As Boolean

    blnFileExists = False

    For Each objFile In ActiveWeb.AllFiles
        If objFile.Name = strFileToOpen Then
            If objFile.IsOpen = True Then
                MsgBox "This file is open; try again later."
                CheckForOpenFile = False
                blnFileExists = True
                Exit For
            Else
                objFile.Edit fpPageViewNormal
                CheckForOpenFile = True
                Exit For
                blnFileExists = True
            End If
        End If
    Next

    If blnFileExists = False Then
        MsgBox "File (" & strFileToOpen & ") doesn't exist."
    End If

End Function


'Use the following subroutine to call the preceding function.
Sub CallCheckForOpenFile()
    Call CheckForOpenFile(strFileToOpen:="default.htm")
End Sub

Finding and Replacing Text

In FrontPage 2003, FrontPage 2002, and FrontPage 2000, you can search for and replace text in HTML pages in two ways. One way is by using the SearchInfo object, which was added in FrontPage 2003. The other way is to use the IHTMLTxtRange object.

Using the SearchInfo object, you can create customized, conditional searches that look for code in specific instances. For example, you can replace all B elements with I elements inside TD elements only. To do this, you use a query string that adheres to a defined XML schema. You can also specify a query string that finds and replaces text by using a regular expression. The first example below shows how to use the SearchInfo object. For more information, see Extending Find and Replace for Microsoft Office FrontPage 2003.

In versions prior to FrontPage 2003, you can use the IHTMLTxtRange object to perform full text search and replace. The FindInFrontPage function in the second example below uses the findText method of the IHTMLTxtRange object to locate an instance of the specified string in the specified page, and then either inserts the string or replaces the specified string with another string. The function returns a Boolean representing whether the function found the search string and successfully added the text.

The objects used in these examples are as follows:

  • SearchInfo
  • PageWindowEx
  • IHTMLTxtRange
  • IHTMLBody
  • IHTMLDocument

Finding and Replacing Text Example 1

Sub QueryContents()
    Dim objSearch As SearchInfo
    Dim objRange As IHTMLTxtRange
    Dim objLimits As IHTMLTxtRange
    Dim strQuery As String
    Dim blnFoundMatch As Boolean

    'Create a query to find a TD element and
    'add an align attribute to the tag.
    strQuery = "<?xml version=""1.0""?>" & _
        "<fpquery version=""1.0"">" & _
        "<find tag=""b"">" & _
        "<rule type=""insideTag"" tag=""td"" />" & _
        "</find>" & _
        "<replace type=""changeTag"" tag=""i"" />" & _
        "</fpquery>"

    Set objRange = ActiveDocument.body.createTextRange
    Set objLimits = ActiveDocument.body.createTextRange
    Set objSearch = Application.CreateSearchInfo

    objSearch.Action = fpSearchFindTag
    objSearch.QueryContents = strQuery

    Do
        blnFoundMatch = Application.ActiveDocument.Find(objSearch, objLimits, objRange)
    Loop While blnFoundMatch = True
End Sub

Finding and Replacing Text Example 2

Function FindInFrontPage(ByRef objTargetPage As PageWindow, _
        ByVal strFind As String, ByVal blnMatchCase As Boolean, _
        ByVal blnFindWholeWord As Boolean, ByVal strText As String, _
        ByVal blnInsert As Boolean) As Boolean

    Dim objBody As IHTMLBodyElement
    Dim objTextRange As IHTMLTxtRange
    Dim blnFound As Boolean
    Dim lngFlags As Long

    Set objBody = objTargetPage.Document.body
    Set objTextRange = objBody.createTextRange

    FindInFrontPage = False

    If blnMatchCase = True Then lngFlags = lngFlags + 4
    If blnFindWholeWord = True Then lngFlags = lngFlags + 2

    objTextRange.collapse True

    Do
        blnFound = objTextRange.FindText(String:=strFind, _
            flags:=lngFlags)

        If blnFound Then
            If blnInsert = True Then
                objTextRange.collapse False
            End If
            objTextRange.Text = strText
            FindInFrontPage = True
            Exit Function
        End If
    Loop While blnFound = True

    Set objBody = Nothing
    Set objTextRange = Nothing

End Function


'Use the following subroutine to call the preceding function.
Sub CallFindInFrontPage()
    Dim blnFound As String
    Dim objPageWindow As PageWindow

    Set objPageWindow = Application.LocatePage( _
        DocumentURL:="example.htm", ViewMode:=fpPageViewNormal)

    blnFound = FindInFrontPage(objTargetPage:=objPageWindow, _
        strFind:="text to find", blnMatchCase:=True, _
        blnFindWholeWord:=True, strText:="text to add or replace", _
        blnInsert:=False)

    Select Case blnFound
        Case True
            MsgBox "Search text found and new text added successfully."
        Case False
            MsgBox "Unable to locate search text."
    End Select

End Sub

Inserting an Interactive Button

In FrontPage 2003, you can programmatically add interactive buttons to Web pages using the InsertInteractiveButton method of the FPHTMLDocument object. The following example adds the "Glow Capsule 1" button. When you add an interactive button to a Web page, FrontPage inserts the necessary scripts. When you remove an interactive button from a Web page, FrontPage removes the scripts.

The objects used in this example are as follows:

  • FPHTMLDocument
  • IHTMLTxtRange

Inserting an Interactive Button Example

Sub InsertNewButton()
    Dim objSelection As IHTMLTxtRange

    Set objSelection = ActiveDocument.Selection.createRange

    ActiveDocument.InsertInteractiveButton objSelection, "fp-btn:Glow Capsule 1", _
        "Home", 200, 50, "http://www.microsoft.com", "_blank"
End Sub

Opening and Editing Files

In FrontPage 2003 and FrontPage 2002, using the Page object model, you can modify the HTML contained in a page.

The first example opens every page in the root folder of the active Web, inserts a META element that indicates that the page has been modified, and then saves and closes the page. This is a powerful routine in that it could do anything, such as remove HTML or add scripts.

The second example performs a task similar to the first example in that it opens and edits the files in the active Web site. However, the AllFiles property allows you to open all the files associated with the Web site. The If statement allows you to specify that the routine open only Web pages. Otherwise, it would open all files, including cascading style sheets, script files, and images. When the condition is met, the routine treats the HTML in the document as a string and performs a Replace function against the string. This allows you to search for (and replace) strings that include string constants, such as vbTab and vbCrLf, or character values, such as Chr(9) and Chr(13).

The objects used in this example are as follows:

  • WebFile
  • WebFiles
  • PageWindowEx
  • FPHTMLDocument
  • IHTMLElement

Opening and Editing Files Example 1

Sub OpenAndEditPages()
    Dim objPage As FPHTMLDocument
    Dim objFile As WebFile
    Dim objPageWindow As PageWindowEx
    Dim objHead As IHTMLElement
    Dim strMetaTag As String

    strMetaTag = "<meta name=""modifiedby"" " & _
        "content=""FrontPage Programmability"">" & vbCrLf & _
        vbTab & "<meta name=""modifieddate"" " & _
        "content=""" & Date & """>" & vbCrLf

    For Each objFile In ActiveWeb.RootFolder.Files
        If objFile.Extension = "htm" Or objFile.Extension = "html" Then
            objFile.Open
            Set objPageWindow = ActivePageWindow
            Set objPage = objPageWindow.Document

            'Add meta tag to each of the pages.
            Set objHead = objPage.all.tags("head").Item(0)
            Call objHead.insertAdjacentHTML("BeforeEnd", strMetaTag)

            'Now save and close the page window.
            objPageWindow.SaveAs objPageWindow.Document.Url
            objPageWindow.Close False
        End If
    Next objFile
End Sub

Opening and Editing Files Example 2

Sub SearchAndReplaceHTML()
    Dim objFile As WebFile
    Dim strPageHTML As String
    Dim strSearch As String
    Dim strReplace As String

    'String for which to to search.
    strSearch = "<!doctype HTML PUBLIC ""-//W3C//DTD " & _
        "HTML 3.2 Final//EN"">"

    'String with which to replace.
    strReplace = "<!doctype HTML PUBLIC ""-//W3C//DTD " & _
        "HTML 4.0 Final//EN"">"

    For Each objFile In ActiveWeb.AllFiles
        If objFile.Extension = "htm" OR objFile.Extension = "html" Then
            objFile.Open

            'When you open the file, it becomes the active document.
            strPageHTML = ActiveDocument.DocumentHTML

            'Search for search string and replace with replace string.
            'Set the HTML of the active document to the new string.
            If InStr(1, strPageHTML, strSearch) > 0 Then
                strPageHTML = Replace(strPageHTML, strSearch, _
                    strReplace)
                ActiveDocument.DocumentHTML = strPageHTML
            End If

            'Close the document in the active page window and
            'force it to save.
            ActivePageWindow.Close True
        End If
    Next objFile

End Sub

Publishing a Web Site to Multiple Locations

In FrontPage 2003, FrontPage 2002, and FrontPage 2000, using the Web object model, you can easily publish a Web site to multiple locations. The following example uses a For loop to pull values from an array of strings. Each string in the array contains the path used to publish the active Web site. The CallPublishToMultipleLocations subroutine shows how to populate the String array and pass it into the PublishToMultipleLocations subroutine.

The object used in this example is as follows:

  • WebEx

Publishing a Web Site to Multiple Locations Example

Sub PublishToMultipleLocations(SiteURL() As String)
    Dim intCount As Integer
    Dim strSite As String

    For intCount = LBound(SiteURL) To UBound(SiteURL)
        strSite = SiteURL(intCount)
        ActiveWeb.Publish strSite
    Next
End Sub


Sub CallPublishToMultipleLocations()
    Dim strURL(1 To 3) As String

    strURL(1) = "http://www.cohowinery.com"
    strURL(2) = "http://mirror1.cohowinery.com"
    strURL(3) = "http://mirror2.cohowinery.com"

    Call PublishToMultipleLocations(strURL)

End Sub

Saving a Page

In FrontPage 2003 and FrontPage 2002, the first example uses the Save method of the PageWindowEx object to save the page displayed in the active page window; if it is a page with frames, the code saves the frames pages as well. For unsaved pages, you must use the SaveAs method.

The second example uses the ForceSave parameter of the Close method to save the page displayed in the active page window.

The object used in this example is as follows:

  • PageWindowEx

Saving a Page Example

Sub PageWindowSave()
    Dim objPageWindow As PageWindowEx
    Dim intCount As Integer

    ActivePageWindow.Save

    For intCount = 0 To ActivePageWindow.FrameWindow.frames.Length – 1
        Set objPageWindow = LocatePage(ActivePageWindow.FrameWindow _
            .frames(intCount).Document.Url, fpPageViewNoWindow)
        objPageWindow.Save
        objPageWindow.Close
    Next intCount
End Sub

Selecting Files from the File Open Dialog Box

In FrontPage 2003 and FrontPage 2002, the Microsoft FrontPage Visual Basic for Applications (VBA) object models provide access to the Microsoft Office System core object model. This includes access to the FileDialog object and the dialog boxes that you can access through the FileDialog object. For more information, see Using the FileDialog Objects.

The following code example shows how to open files by using the FileDialog object. The objects used in this example are as follows:

  • FileDialog
  • WebEx
  • WebWindowEx

Selecting Files from the File Open Dialog Box Example

Sub SelectFilesFromFileOpenDialog()
    Dim objFileOpen As FileDialog
    Dim strFolder As String
    Dim strFile As Variant
    Dim intCount As Integer

    'Creates the File Open dialog object.
    Set objFileOpen = FrontPage.Application.FileDialog(msoFileDialogOpen)

    'Specifies the root folder of the active Web site as the startup folder.
    strFolder = ActiveWeb.RootFolder
    strFolder = Replace(strFolder, "file:///", "")
    strFolder = Replace(strFolder, "/", "\")
    objFileOpen.InitialFileName = strFolder

    'Opens the selected files in FrontPage.
    If objFileOpen.Show < 0 Then
        For Each strFile In objFileOpen.SelectedItems
            ActiveWebWindow.PageWindows.Add strFile
        Next
    End If
End Sub

Getting Started

Now that you have learned the basics and have some simple macros to play with, you are just getting started with automating FrontPage. Besides creating macros, you can create forms that request user input, you can add shortcuts to access your macros from the menus and toolbars, and you can create full add-in projects that you can distribute to others. For more information on automating and extending FrontPage, see Extending the FrontPage Application, which will be available soon. You can also find a section on working with VBA in FrontPage in the book Using Microsoft Office FrontPage 2003, written by Paul Colligan and Jim Cheshire and published by QUE Publishing.