Gordon McComb

Sharing Variables and Running Macros from Visual Basic .NET

Set and read variables for use in wordperfect; run any macro

In the introduction tutorial you learned how to use the magic of Visual Basic .NET "interop" to set up a link between a VB.NET application and WordPerfect. There's even more power awaiting you by taking advantage of another automation technique available since WordPerfect version 9.

In this tutorial you'll learn how to apply the functionality of the PerfectFit module that comes with WordPerfect.

With PerfectFit, you can:

  • Set and read variables between a VB.NET program and WordPerfect. You might use this feature, for example, to build a VB.NET application that displays an interactive dialog box that prompts for user entry such as name, address, case and matter numbers, and other pertinent data. With PerfectFit, you can then "pass" the data directly to WordPerfect for use in a macro or merge.
  • Run any macro quickly and easily. Continuing with the previous example, once the data in the user form has been entered, you can launch a macro that reads the variables previously set, and inserts the data into a boilerplate form.

Let's get started. To complete this tutorial you'll need a copy of Visual Basic 2008 or later (see the sidebar on how to get a free copy). For your convenience, all program files are provided in a single download. Find the link at the bottom of this page.

Understanding WordPerfect Variables

The PerfectFit demonstrator shows how to set, retrieve, and delete what's known as persistent macro variables. In WordPerfect, there are three types of variables for use in macros. All three are variables; the difference is how long the variable lasts in memory, and how the variables can be "seen" by other macros.

  • Local variables have the shortest life, and have the least visibility to other macros. Unless you tell it otherwise, a variable you create in a WordPerfect macro is automatically made a local variable. The variable can only be used in the macro, procedure, or function in which it was defined.
  • Global variables are visible to all macros that are run as a group. If you define a variable in Macro-A, and that macro runs Macro-B, your global variable is shared between them. The variable is removed from memory when all macro execution stops.
  • Persistent variables are not only visible to all macros, but even to merges. And, the variable stays in memory until you quit WordPerfect. (Technically, the variable is lost when the PerfectScript utility program shuts down. But as PerfectScript and WordPerfect typically run together, it's more or less all the same thing.)

Persistent variables are the kind that can be created in, and read by, a VB.NET application. You may use persistent variables to pass data between your VB.NET program and WordPerfect.

The possibilities are nearly endless, but you can use this functionality whenever you need a seamless way to to communicate data between the two programs. As we'll see, since it's possible to also run macros using the PerfectFit functions, once you set a variable you can then launch a macro that performs some process on the data you've previously set.

We've said it before, but it bears repeating again: Persistent variables are also "visible" to merges. To fetch a persistent variable you use the VARIABLE merge code. Set a variable in your VB.NET program, then start a merge. Reference the variable with a VARIABLE code, and the data is automatically inserted into the merged document. Pretty cool stuff.

Creating the PerfectFit Demo Application

The PerfectFit demonstrator consists of a single form with five buttons on it. The buttons are provided to show how to use the various functions of the demonstration.

Button names and text labels are:

btnCreateVar - Create VBNetVar variable for use in WordPerfect

btnDeleteVar - Delete VBNetVar variable

btnGetVar - Get MyPersistVar variable created in WordPerfect macro

btnPlayMacro - Play a macro

btnClose - Close

The buttons are placed on Form1. Enter the following code for Form1:

Option Strict On
Imports System.Runtime.InteropServices
Public Class Form1
  Private pf As PerfectFit.PerfectScript

  Private Sub Form1_Load(ByVal sender As Object, _
     ByVal e As System.EventArgs) Handles Me.Load
    pf = New PerfectFit.PerfectScript
  End Sub

  Private Sub Form1_FormClosing(ByVal sender As Object, _
      ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    If (Not pf Is Nothing) Then
      pf = Nothing
    End If
  End Sub

  Private Sub btnClose_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles btnClose.Click
  End Sub

  Private Sub btnCreateVar_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles btnCreateVar.Click
    PSSetVariable("VBNetVar", "New Var Value")
  End Sub

  Private Sub btnGetVar_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles btnGetVar.Click
    Catch ex As NullReferenceException
      MsgBox("Variable probably doesn't exist. Run the" & _
         " PersistVarTest.wcm macro to set the variable.")
    Catch ex As Exception
    End Try
  End Sub

  Private Sub btnDeleteVar_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles btnDeleteVar.Click
  End Sub

  Private Sub btnPlayMacro_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles btnPlayMacro.Click
    PSPlayMacro(Application.StartupPath & "\PerfectFitMacroTest.wcm")
  End Sub

  Private Function PSSetVariable(ByVal VariableName As String, _
      ByVal VariableValue As String) As Boolean
    Dim tObj As Object = New Object
    pf.VariableName = VariableName
    tObj = VariableValue
    Return (pf.SetPerfectScriptVariable(tObj))
  End Function

  Private Function PSGetVariable(ByVal VariableName As String) As String
    Dim tObj As Object = New Object
    pf.VariableName = VariableName
    Return (pf.GetPerfectScriptVariable().ToString)
  End Function

  Private Function PSDeleteVariable(ByVal VariableName As String) As Boolean
    pf.VariableName = VariableName
    Return (pf.DiscardPerfectScriptVariable)
  End Function

  Private Function PSPlayMacro(ByVal MacroName As String) As Boolean
    pf.ScriptName = """" & MacroName & """"
    Return (pf.ScriptPlay())
  End Function

End Class

Referencing PerfectFit On Your Computer

Before you can use the PerfectFit demonstrator program you have to reference the correct version of PerfectFit that's on your computer. If you try to compile and run the application now you'll get an error.

Each version of WordPerfect, from version 9 to the current one, has a different PerfectFit module. Once you add a reference to this module you can try out the demonstrator. To reference your PerfectFit module:

  • Choose Project, Add Reference
  • Click the COM tab
  • Scroll down to PerfectScript *, where the * is the version(s) of WordPerfect you have installed. Since you can have more than one version of WordPerfect installed on a single computer, there may be more than one PerfectScript * items listed. Pick the one you want, then click OK.

You may now compile and run the application by pressing F5.

Inside the PerfectFit Demo

Let's review the code to understand how it works.

Loading and Unloading the PerfectFit Library

In the Form1_Load and Form1_Closing methods the PerfectFit library is loaded into memory. You will notice that when you run the PerfectFit demonstrator that the PerfectScript program splash screen will briefly appear. (The splash screen only appears the first time you start the demo if WordPerfect is already running.)

While Windows should do it automatically for you, just to be on the safe side the _Closing method cleans up the reference to the PerfectFit library object.

Creating (Setting) a Variable

The btnCreateVar_Click method shows how to use PerfectFit to define a new persistent variable. You'd use this code to assign a variable that can then be used inside WordPerfect.

To make it easier to adapt the demonstrator code to a full-fledged application, the method calls a separate function that we've named PSSetVariable. This function takes two arguments: the name of the variable to set, and the content of the variable. In this case, we set a variable named VBNetVar with the string, "New Var Value."

Be sure to use only valid variable names, or PerfectFit won't set your variable. Variables should contain only letters and numbers, and should not start with a number.

Getting a Variable

The btnGetVar_Click method shows how to retrieve an existing persistent variable that's already been set, presumably by a macro or merge. Persistent variables are set in a macro by adding the keyword Persist to the variable assignment.

A sample macro that sets a persistent variable is included with the download project files. The name of the macro is PersistVarTest.wcm, and it contains the following simple code:

Persist(MyPersistVar = "This is a persistent variable set in a macro.")
MessageBox (;; VBNetVar)

As with setting a variable, we've added a generic function - PSGetVariable - to get a variable. The routine expects the name of the variable to get; the return value is the variable contents.

Note the explicit error trap if the variable you're trying to get doesn't exist. You should include this trap in all cases. If you'd like to include a pre-validation test, you can make use of the PerfectScriptVariableExists function that's part of the PerfectFit library.

Deleting a Variable

The btnDeleteVar_Click method and PSDeleteVariable function show how to remove a persistent variable from memory. The variable is removed when you exit WordPerfect (okay, PerfectScript), but you might want to explicitly clean up no longer needed variables to keep down clutter.

Running a Macro

Let's remember you can also use the PerfectFit module to run a macro. You simply provide the location and name of the macro, and PerfectFit takes care of the rest. If WordPerfect needs to be running to complete the macro, it is automatically started.

For demonstration we've included a test macro, PerfectFitMacroTest.wcm, that is launched in btnPlayMacro_Click. That method calls a function, PSPlayMacro, which does the actual work. The PerfectFitMacroTest.wcm macro is simple, and contains a WordPerfect Application reference, and a Type statement.

Application (WordPerfect; "WordPerfect"; Default!; "EN")
Type("This is a macro launched from VB.NET.")

When the macro runs it prints the text "This is a macro launched from VB.NET."

PerfectFit also lets you set startup arguments for macros, and run template macros. For simplicity we've left out these methods, but you can view what other methods are available by clicking the Object Browser button in the VB.NET toolbar. Find the PerfectFit library, and expand it.

Putting PerfectFit to Use

Now that you know how to share variables with WordPerfect, and run any macro, how might you use this functionality? Here are just a couple of ideas - the possibilities are endless!

  • Build a database back end in VB.NET that connects to the SQL or other database server in your office. In your application you can select a record, then create variables to transfer the data for use in WordPerfect. Then, in WordPerfect, you can run a merge that references those variables by using VARIABLE codes. Where ever there is a VARIABLE code, the data is inserted.
  • Same as above, but you can use the variables you've defined in your Visual Basic .NET program in a macro. Once you set the variables, use VB.NET launch a macro. That macro might open a boilerplate document, then locate specific bookmarks. At each bookmark you insert the contents of the corresponding variable.
  • Going the other way, you can build a macro that creates a query from input provided in a PerfectScript dialog box. The query is placed into a persistent variable. Have your macro then launch your VB.NET application. Your program reads the variable, and then processes the request. It might do a database lookup, send out emails, create customer billing, or any of an infinite number of possible tasks.
Download the PerfectFit demonstration files by right-clicking, then saving to your computer. Unzip the files to your usual VB.NET projects directory.

Text and project Copyright © 2010, Gordon McComb. Released under Creative Commons Attribution-Share Alike license. You may use, reproduce, modify, and distribute this code, as long as the above copyright and attribution is retained.