FrontPage Publishing with Visual Basic for Applications

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

 

Jimco

February 2003

Applies to:
    Microsoft® FrontPage® 2002 with Visual Basic® for Applications

Summary: Learn how to publish a FrontPage Web site using Visual Basic for Applications (VBA) and macros. (16 printed pages)

Contents

Introduction
Writing Macros in FrontPage
Creating a Simple Macro
Creating a Custom Form
Writing the Publish Web Macro
Adding the Code
Setting Publish Options
Publishing the Web
The Last Step
Conclusion

Introduction

With the release of the Microsoft® FrontPage® 2000 Web site creation and management tool, Microsoft added Visual Basic® for Applications (VBA) for the development of macros. With macros, you can easily automate repetitive tasks and add functionality to FrontPage. However, because FrontPage has no macro recorder, not many FrontPage users have taken advantage of this powerful feature.

This article will demonstrate how to use VBA to publish a FrontPage Web site. With a macro, you can specify publish options, recalculate hyperlinks, and check for unsaved files prior to publishing. Using the examples in this article, you will be able to get a taste of the power that VBA brings to FrontPage.

Writing Macros in FrontPage

Macros are written using the Visual Basic Editor. By default, the Visual Basic Editor contains a user module called Module1. This user module is simply a file that contains code that executes when you run a macro in FrontPage. We will discuss adding code to a user module in the Creating a Simple Macro section below.

Note   The Help files for VBA in FrontPage are set to install on first use. To install the Help files, on the Help menu, click Microsoft Visual Basic Help and then choose Install Missing Help Files. The documentation provided by the Help files is very comprehensive.

One of the most useful features in the Visual Basic Editor is the Object Browser. The Object Browser allows you to view all the objects, properties, methods and events available to you. The Object Browser also provides quick and easy access to online help for each item displayed within it. Simply right-click the object, property, method or event and choose Help from the menu to get detailed help on that item.

Let's review the help information for the Publish method in FrontPage using the Object Browser.

To learn about the Publish method

  1. Press F2 to open the Object Browser.
  2. In the Libraries drop-down list, choose FrontPage.
  3. In the Classes list, select WebEx. This will populate the Members list with all the members of the WebEx object. (The WebEx object represents a FrontPage Web site.)
  4. In the Members list, right-click the Publish method and then click Help.

Using the Help files, you can see documentation and examples that will make writing your own VBA macros easy.

Note   For more information, see FrontPage Visual Basic Editor Help.

Creating a Simple Macro

Now let's create a simple macro that we can build upon to create our Publish Web macro.

In the Visual Basic Editor's Project pane (located in the upper-left corner), double-click on Module1 to open the code window for that module (you may need to click the plus sign next to the Modules folder to expand it first). Enter the following code into Module1's code window:

Public Sub PublishWebMacro()
    ' check to see if a Web is open...
    If Not ActiveWeb Is Nothing Then
        MsgBox "The current Web's URL is " & ActiveWeb.URL
    End If
End Sub 

After you have entered the code, open a Web site in FrontPage and then run the macro.

To run the macro

  1. On the Tools menu, point to Macro, and then click Macros.
  2. Select PublishWebMacro, and then click Run. A message box will be displayed with the URL of the current Web site.

In this example, we wrote a simple procedure in Visual Basic for Applications. We checked to see if the ActiveWeb object contained a reference to a Web. The ActiveWeb object holds a reference to the Web site currently open in FrontPage. If the ActiveWeb object is equal to Nothing, then we know that a Web site is not currently open in FrontPage.

This is a commonly used technique when writing macros. Very often, your macro will do something with the Web site that is currently open in FrontPage. You can use this method to easily determine if there is an open Web site in FrontPage. If there isn't, you can display a helpful reminder to your user. That is what we'll do in our Publish Web macro later in this article.

Creating a Custom Form

With custom forms (called UserForms in the Visual Basic Editor), you can collect information from the users of your macro or allow your users to interact with your macro. Custom forms add power to your macros. In our Publish Web macro, we will use a custom form to allow our users to specify where the Web site should be published and publish options for the Web site. Without a custom form, this level of control would not be possible.

Writing the Publish Web Macro

Now that we have a general idea of how to write a macro, let's get down to business! We're going to write a macro that will publish a FrontPage Web site, and we want to add some additional functionality that isn't included in the FrontPage Publish feature. We want our macro to:

  • Recalculate hyperlinks on the Web site prior to publishing
  • Save any unsaved changes prior to publishing
  • Publish the current Web site with the options that the user specifies

The first thing that we need to do is add a blank custom form to our macro. To do that, right-click Microsoft_FrontPage in the Project Explorer pane, point to Insert, and click UserForm. This will insert a blank form into your project and open the Toolbox.

The Toolbox contains the controls that we need to add functionality to the new form. You add controls to the form by clicking the control's icon in the Toolbox and then drawing the control on the form with your mouse. After you add a control, if you select it with your mouse, the Properties pane will show all the properties of that control.

We will be using the Label control, TextBox control, CheckBox control and CommandButton control on our form. Add these controls to the form and set properties as follows:

UserForm1  
Name frmMain
Caption Publish Web
Height 236
Width 363
Label1  
Name lblInformation
Caption Destination URL or disk location:
Left 12
Top 12
Width 288
Label2  
Name lblOptions
Caption Publish Options
Left 12
Top 69
Width 70
TextBox1  
Name txtDestination
Left 12
Top 24
Width 300
CheckBox1  
Name chkChangedPages
Accelerator c
Caption Publish changed pages only
Left 12
Top 84
Width 133
CheckBox2  
Name chkAddToExisting
Accelerator e
Caption Add to existing Web
Left 12
Top 106
Width 133
CheckBox3  
Name chkDeleteUnmatched
Accelerator u
Caption Delete unmatched files
Enabled False
Left 24
Top 124
Width 133
CheckBox4  
Name chkIncludeSubwebs
Accelerator s
Caption Include subwebs
Left 12
Top 149
Width 133
CheckBox5  
Name chkRecalculate
Accelerator R
Caption Recalculate before publish
Left 180
Top 84
Width 133
CheckBox6  
Name chkSaveUnsaved
Accelerator B
Caption Save unsaved pages before publishing
Left 180
Top 106
Width 133
CommandButton1  
Name cmdCancel
Cancel True
Caption Cancel
Height 18
Left 222
Top 186
Width 60
CommandButton2  
Name cmdPublish
Caption Publish
Default True
Height 18
Left 288
Top 186
Width 60

Once you have finished adding the controls and setting the properties, your form should look something like the form pictured below.

Aa140110.odc_fppublishingwithvba01(en-us,office.10).gif

Figure 1. The custom form for the Publish Web macro

Every control on the form has events that are associated with it. For example, the control called cmdPublish has an event called Click that runs when a user clicks the button. To add functionality to the form, we will write our macro code inside the events for the form.

Note   For more information about the properties and events for each control, see the Object Browser and Visual Basic Editor Help.

When a user runs the PublishWebMacro subroutine, frmMain will be displayed. The user then can specify the destination URL for the Web site and set the options for publishing the Web site. Then when the Publish button is clicked, the Web site will be published using the options that the user specified.

Adding the Code

Most of the code in this macro is located in the Click event for the cmdPublish button. Right-click the form that we have just added and click View Code. This will open the code window for the form. At the top of the code window are two drop-down lists. The left list contains an entry for each control on the form, and the right list is populated with the events for the control that is selected on the left.

To add the code for the Click event of our button

  • In the left drop-down list, select cmdPublish.
  • In the right drop-down list, select Click.
  • Paste the following code between the two lines that the Visual Basic Editor inserted into your code, so that your code window looks like this:
Private Sub cmdPublish_Click()
    ' Declare some variables...
    Dim strMsg As String
    Dim fpPublishFlags As FpWebPublishFlags
    Dim vbReturn As VbMsgBoxResult
    Dim boolPublishResult As Boolean
    ' Check to make sure that the user entered a destination URL...
    If txtDestination.Text = "" Then
        strMsg = "Please enter a publish destination."
    ' Check to see if the destination URL entered is valid
    ' by checking to see if it begins with http:// or https:// or 
    ' is a disk-based Web...
    ElseIf UCase(Left(txtDestination.Text, 7)) <> "HTTP://" And _
        UCase(Left(txtDestination.Text, 8)) <> "HTTPS://" And _
        InStr(2, txtDestination.Text, ":\") = 0 Then
        strMsg = "The publish destination is not valid.  Please try 
          again."
    End If
    ' Configure Web publish flags from our options checkboxes...
    If chkChangedPages.Value = True Then
        fpPublishFlags = fpPublishIncremental
    End If
    If chkIncludeSubwebs.Value = True Then
        fpPublishFlags = fpPublishFlags + fpPublishCopySubwebs
    End If
    If chkDeleteUnmatched.Value = False And chkAddToExisting.Value = True 
      Then
        fpPublishFlags = fpPublishFlags + fpPublishNoDeleteUnmatched
    End If
    ' Check to see if the strMsg variable is empty.  
    ' If it is not, there is a problem with the entries...
    If strMsg <> "" Then
        ' Display a message to the user informing them of the problem...
        MsgBox strMsg, vbExclamation + vbOKOnly, "Publish Web"
        ' Select the text in txtDestination and set the focus to it...
        With txtDestination
            .SelStart = 0
            .SelLength = Len(.Text)
            .SetFocus
        End With
    Else    ' No problems with user input...
        ' If we've specified to recalc before publish, do that now...
        If chkRecalculate.Value = True Then ActiveWeb.RecalcHyperlinks
        ' If we've specified to save unsaved pages, do that now...
        If chkSaveUnsaved.Value = True Then
            ' Loop through all open pages and see if they are unsaved...
            '----------------------------------------
            ' Create a variable to hold a reference to a PageWindowEx 
              object...
            Dim pw As PageWindowEx
            ' Use a For...Next loop to loop through all PageWindows, 
            ' check if they are unsaved, and save if they are...
            For Each pw In ActiveWebWindow.PageWindows
                If pw.IsDirty Then
                    pw.Save
                End If
            Next
        End If
        ' Publish the Web...
        On Error GoTo ErrorHandler
        boolPublishResult = PublishWeb(txtDestination.Text, 
          fpPublishFlags)
        ' Display a message telling the user that the Web was published.
        MsgBox "The Web " & ActiveWeb.Url & _
          " was successfully published.", vbInformation, _
          "Publish Web"
        ' Unload the UserForm...
        Unload frmMain
    End If
ExitSub:
    Exit Sub
ErrorHandler:
    If InStr(1, Err.Description, "Web already exists") <> 0 Then
        ' FrontPage returned an error saying the Web already exists...
        vbReturn = MsgBox("The destination Web already exists." + _
          vbCrLf + vbCrLf + _
          "Would you like to add the current Web to the destination 
            Web?", _
          vbYesNo + vbExclamation, "Publish Web")
        ' If the user answers 'YES'...
        If vbReturn = vbYes Then
            ' Add the flag "fpPublishAddToExistingWeb" to 
            ' our FpWebPublishFlags...
            fpPublishFlags = fpPublishFlags + _
              fpPublishAddToExistingWeb + fpPublishNoDeleteUnmatched
            ' Clear the err object...
            Err.Clear
            ' ... and call the PublishWeb function again...
            boolPublishResult = PublishWeb(txtDestination.Text, 
              fpPublishFlags)
        Else    ' Don't add to existing Web...
            ' Display a message to the user indicating that they 
            ' need to specify a new location...
            MsgBox "Please specify a new destination URL or disk 
              location.", _
            vbOKOnly + vbExclamation, "Publish Web"
            ' Clear the err object...
            Err.Clear
            ' ... and exit out of the subroutine.
            GoTo ExitSub
        End If
    Else    ' An error occurred other than "Web already exists..."
        ' Display the error to the user...
        vbReturn = MsgBox(Err.Description + vbCrLf + vbCrLf + _
          "Publishing of the Web failed.", vbOKOnly + _
          vbCritical, "Publish Web")
          ' Exit the subroutine...
          GoTo ExitSub
    End If
End Sub

Let's break down the code in that event and examine it in detail. After we've declared some variables for our procedure, we check to see if the user entered a valid destination for the Web site.

' Check to make sure that the user entered a destination URL...
If txtDestination.Text = "" Then
    strMsg = "Please enter a publish destination."
    ' Check to see if the destination URL entered is valid
    ' by checking to see if it begins with http:// or https:// 
    'or is a disk-based Web...
ElseIf UCase(Left(txtDestination.Text, 7)) <> "HTTP://" And _
    UCase(Left(txtDestination.Text, 8)) <> "HTTPS://" And _
    InStr(2, txtDestination.Text, ":\") = 0 Then
    strMsg = "The publish destination is not valid.  Please try again."
End If

The first thing we do is check to see if the user left the destination URL blank. If so, we set the value of the strMsg variable to a suitable message. If the user did specify a destination URL, we check to see if it is a valid URL or a disk-based location. We do that by performing the following checks on the value entered:

  • Does it begin with "http://"?
  • Does it begin with "https://"?
  • Do the second and third characters equal ":\"?

If none of these checks apply, we know that the destination URL entered is invalid. Therefore, we set the strMsg variable to an appropriate message so that we can inform the user of the error.

Setting Publish Options

The next step is to check to see which options the user chose for publishing the Web site. We do that by checking which check boxes the user selected and setting the options accordingly.

The publish flags that we allow the users of our macro to set are as follows:

  • FpPublishIncremental—When this flag is set, FrontPage publishes only pages that have changed since the last publish. This is the equivalent to setting the Changed Pages Only option in FrontPage when publishing.

  • fpPublishCopySubwebs—This flag specifies that any subwebs of the current Web site will be published along with it. This is the equivalent to selecting the Include Subwebs option in FrontPage when publishing.

  • fpPublishNoDeleteUnmatched—If this flag is set, files that exist in the remote Web site but not in the local Web site are deleted from the remote Web site when the local Web site is published.

  • fpPublishAddToExistingWeb—This flag is set whenever you are publishing to a Web site that already exists. If this flag is not set and the destination Web site already exists, the Web site will not be published. If this flag is set but the destination Web site does not exist, the Web site will not be published.

    Note   For information on the different publish flags (options), see the Publish method in Visual Basic Editor Help.

To determine which flags to set when we publish, we check to see which check boxes have been selected by examining the Value property of each check box. If the value is True, the check box has been selected. Otherwise, it has not been selected.

' Configure Web publish flags from our options checkboxes...
If chkChangedPages.Value = True Then
    fpPublishFlags = fpPublishIncremental
End If
If chkIncludeSubwebs.Value = True Then
    fpPublishFlags = fpPublishFlags + fpPublishCopySubwebs
End If
If chkDeleteUnmatched.Value = False And chkAddToExisting.Value = True Then
    fpPublishFlags = fpPublishFlags + fpPublishNoDeleteUnmatched
End If

The next step in our macro is to determine whether or not the user wants to recalculate hyperlinks and/or save all unsaved pages before publishing. Here is the code we use to accomplish that:

' If we've specified to recalc before publish, do that now...
If chkRecalculate.Value = True Then ActiveWeb.RecalcHyperlinks
' If we've specified to save unsaved pages, do that now...
If chkSaveUnsaved.Value = True Then
    ' Loop through all open pages and see if they are unsaved...
    '----------------------------------------
    ' Create a variable to hold a reference to a PageWindowEx object...
    Dim pw As PageWindowEx
    ' Use a For...Next loop to loop through all PageWindows,
    ' check if they are unsaved, and save if they are...
    For Each pw In ActiveWebWindow.PageWindows
        If pw.IsDirty Then
            pw.Save
        End If
    Next
End If

The first thing that we do in this code is to check to see if the Recalculate before publish check box is selected. If it is, we simply call the RecalcHyperlinks method on the active Web site. This method recalculates hyperlinks on the Web site so that all information for the site is completely updated.

After we've done that, we check to see if the Save unsaved pages before publishing check box is selected. If it is, we run through all the open files in FrontPage and, if they are unsaved, we save them. The code for doing that is slightly more complex.

To loop through all open pages, we use the PageWindowEx object. The PageWindowEx object represents an open page in FrontPage. Each PageWindowEx object has many properties associated with it, including the IsDirty property. This property returns True if the page contains unsaved changes and False if it does not.

We use a For . . . Next loop to loop through all open PageWindowEx objects using the PageWindows collection of the ActiveWebWindow object. (A collection is a group of objects of the same type.) The ActiveWebWindow object represents the active FrontPage application window. The PageWindows collection of that object contains one PageWindowEx object for each open page. We simply loop through each one of those and check to see if it is unsaved. If it is, we call the Save method of the PageWindowEx object to save it.

Note   For more information about the PageWindowEx object, the ActiveWebWindow object, and the PageWindows collection, see the Object Browser or Visual Basic Editor Help.

Publishing the Web

Now we're ready to publish our Web site. Earlier we talked about the fpPublishAddToExistingWeb flag. Remember we said that if the destination Web site exists, we must use this flag or the Web site will not be published. Therefore, we need a way to determine if the destination Web site exists when we publish the Web site with our macro. If it does, we need to set the fpPublishAddToExistingWeb constant so that our Web site will publish.

The code that does this is located in the error handling that we have implemented in the Click event of the cmdPublish button. If an error occurs during publishing, we use the Err object to access the error message and act accordingly. Using the error message, we can determine if publishing failed because the Web site already exists. If it did, we add the fpPublishAddToExistingWeb flag and try publishing again. If publishing fails for any other reason, we simply display the error message to the user in a message box.

Here is the code that publishes the Web site and that includes the error handling:

    ' Publish the Web...
    On Error GoTo ErrorHandler
    boolPublishResult = PublishWeb(txtDestination.Text, fpPublishFlags)
    ' Display a message telling the user that the Web was published.
    MsgBox "The Web " & ActiveWeb.Url & _
      " was successfully published.", vbInformation, "Publish Web"
    ' Unload the UserForm...
    Unload frmMain
End If
ExitSub:
    Exit Sub
ErrorHandler:
If InStr(1, Err.Description, "Web already exists") <> 0 Then
    ' FrontPage returned an error saying the Web already exists...
    vbReturn = MsgBox("The destination Web already exists." + _
      vbCrLf + vbCrLf + _
      "Would you like to add the current Web to the destination Web?", _
      vbYesNo + vbExclamation, "Publish Web")
    ' If the user answers 'YES'...
    If vbReturn = vbYes Then
        ' Add the flag "fpPublishAddToExistingWeb" to 
        ' our FpWebPublishFlags...
        fpPublishFlags = fpPublishFlags + _
          fpPublishAddToExistingWeb + fpPublishNoDeleteUnmatched
        ' Clear the err object...
        Err.Clear
        ' ... and call the PublishWeb function again...
        boolPublishResult = PublishWeb(txtDestination.Text, 
          fpPublishFlags)
    Else    ' Don't add to existing Web...
        ' Display a message to the user indicating that they 
        ' need to specify a new location...
        MsgBox "Please specify a new destination URL or disk location.", _
          vbOKOnly + vbExclamation, "Publish Web"
        ' Clear the err object...
        Err.Clear
        ' ... and exit out of the subroutine.
        GoTo ExitSub
    End If
Else    ' An error occurred other than "Web already exists..."
    ' Display the error to the user...
    vbReturn = MsgBox(Err.Description + vbCrLf + vbCrLf + _
      "Publishing of the Web failed.", vbOKOnly + vbCritical, _
      "Publish Web")
    ' Exit the subroutine...
    GoTo ExitSub
End If

Let's break this down a bit. The first line of this code sets up the error handling by using the On Error GoTo statement. After this statement, any errors that occur will cause the code in the ErrorHandler section to run.

Immediately after error handling has been set up, we call the PublishWeb function. Because we have error handing configured, if any errors occur while publishing, they will be handled by our error handling code. We've already reviewed the PublishWeb function. Now let's review what happens if an error occurs while publishing by looking at the ErrorHandler section of code above.

The first thing we do is check to see if the Description property of the Err object indicates that the Web site already exists. If it does, we present the user with the option to add the current Web site to the existing Web site. If the user chooses to do so, we clear the Err object (so we can start again), we add the fpPublishAddToExistingWeb publish flag to the existing publish flags, and we call the PublishWeb function again. If the user chooses not to add to the existing Web site, we simply notify the user that he or she needs to choose a new destination URL.

If any other error occurs, we display a suitable message to the user, indicating that the publishing failed.

The Last Step

The last step in our macro is to add code that will display the custom form to the user. To do that, we need to edit the PublishWebMacro subroutine that we added to Module1 earlier. Edit the PublishWebMacro subroutine so that it contains the following code:

Public Sub PublishWebMacro()
    ' check to see if a Web is open...
    If Not ActiveWeb Is Nothing Then
        frmMain.Show
    Else
        MsgBox "Please open a Web before running " + _
          "this macro.", vbOKOnly + vbInformation, "Publish Web"
    End If
End Sub

Our PublishWebMacro procedure now will check to see if there is an active Web site. If there is, it will show our custom form. If there is not, it will display a message to the user, indicating that the user needs to open a Web site before running our macro.

To run the macro, simply run the macro called PublishWebMacro just as you did before.

Conclusion

As you can see, it is quite easy to add extended functionality to Microsoft FrontPage using Visual Basic for Applications and macros—but it doesn't stop there! Once you learn the object models for FrontPage and how to write VBA macros, you can use other development environments to extend FrontPage even further. You can use the Microsoft Visual Basic development system to write add-ins for FrontPage, or you can use Visual Basic Scripting Edition (VBScript) and Windows Script Host to write scripts that automate FrontPage and then schedule those scripts to run at specific times.

Using VBA in FrontPage, almost anything you can imagine can be automated in FrontPage. As you write your own macros, if you have any questions about the FrontPage object models, there are plenty of resources available to assist you. The Microsoft Office Developer Center is a great resource. You also can access the FrontPage Software Development Kit. If you can't find your answers there, please feel free to ask me by filling out the form available on my Web site at www.jimcoaddins.com.

Happy coding!