Programming Microsoft Access 2000 (Microsoft Programming Series)

The Office Assistant is a friendly help feature in Office. Although developers and power users might not like the Assistant, it is appealing to typical users. The Assistant is relatively easy to program, so you can easily give your custom Office applications the same look and feel as the standard Office applications.

The Assistant object model is shown in Figure 8-3. The top-level Assistant object can appear on the screen with or without its hierarchically dependent Balloon object. Because the Assistant can use a wide range of characters and animations, it can be entertaining and informative without explanatory text. If you want to include explanatory text, you can program Balloon objects to appear with the Assistant. Balloons can include explanatory text or even serve as a simple data entry device. You use the BalloonCheckBox and the BalloonLabel collections with button controls to make your assistants interactive.

Figure 8-3. You use the Assistant object to present an assistant, animate it, and display a balloon.

Assistants

Assistants can add value to an application by conveying visually the various actions that your application is performing. You can further distinguish your custom application by consistently using a specific assistant or by regularly using different assistants but in highly differentiated circumstances. For example, use The Genius assistant representation for help pertaining to computations, but use the F1 robot when offering help about computer system topics. Your development team can adopt a rule to always invoke the working animation for any task that takes more than a couple of seconds.

Showing and animating an assistant

You can easily control the display and animation of an assistant by using the three short procedures shown here: AssistantIdleOn, AssistantNotVisible, and AssistantSearchOn. The AssistantIdleOn procedure contains a single line that sets the Assistant object's Visible property to True. Since msoAnimationIdle is the default animation type (the animation character is idle), the line that sets the Animation property is not needed and is commented out. In addition, this basic animation is part of the core Access library, so you can invoke it without referencing the Microsoft Office 9 Object Library. You can also run the AssistantNotVisible procedure without referencing the Office Object Library.

Sub AssistantIdleOn() 'Setting animation for idle is optional. ' Assistant.Animation = msoAnimationIdle Assistant.Visible = True End Sub Sub AssistantNotVisible() Assistant.Visible = False End Sub Sub AssistantSearchOn() If Assistant.Visible = False Then Assistant.Visible = True Assistant.Animation = msoAnimationSearching End Sub

To change the animation character's behavior to something other than idle, your procedure must set the object's Animation property as well as its Visible property. The AssistantSearchOn procedure causes an Assistant object to display its searching animation. Unlike many of the other animations, the searching animation repeats until you assign a new Animation setting. In addition, your project must have a reference to the Office Object Library for the searching animation to appear. (You can set this manually using the Tools menu in VBE.)

Automatically referencing the Office Object Library

One disadvantage of the AssistantSearchOn procedure is that it assumes a reference to the Office Object Library. If there is none, the procedure fails silently. The assistant appears, but it shows an idle, instead of a searching, animation. One way to handle this problem is to verify whether there is a reference to the Office Object Library and to add one automatically if necessary. Your application can then confidently invoke any animation, or indeed any other property of another shared Office object. The AssistantSearchOn2 and ReferenceOffice procedures below show this solution.

Sub AssistantSearchOn2() ReferenceOffice AssistantSearchOn End Sub Sub ReferenceOffice() Dim ref1 As Reference Dim blnOffice9In As Boolean, mso9Library As String 'Enumerate members of References collection to determine 'whether Office Object Library is already referenced. blnOffice9In = False For Each ref1 In References If ref1.name = "Office" Then blnOffice9In = True End If Next ref1 'If Office Object Library reference is missing, reference it. If blnOffice9In = False Then mso9Library = _ "C:\program files\Microsoft Office\Office\mso9.dll" Application.References.AddFromFile mso9Library End If End Sub

AssistantSearchOn2 is nearly identical to the original procedure for invoking a searching animation. It actually calls AssistantSearchOn, but it calls ReferenceOffice first. ReferenceOffice ensures that the current project has a reference to the Office Object Library. It starts by enumerating all the members of the References collection to determine whether any of them have a Name property of Office. If yes, then the procedure sets a Boolean variable to True. Otherwise, blnOffice9In retains its default setting of False. The second segment of ReferenceOffice creates a reference to the Office Object Library if the Boolean variable is False. Having ensured that the Office Object Library is referenced, AssistantSearchOn2 can invoke the AssistantSeachOn procedure to finish activating the animation.

Displaying a searching animation

You can use the Assistant object to complement the FileSearch object. I already noted that some searches can take a while. In these situations, it is useful to present some kind of cue on the screen to show that your application is doing something. The Assistant's searching animation serves this purpose well.

The following procedure searches the entire C drive for .mdb files and returns a count of the files. By displaying the searching animation just before launching the search and restoring the idle animation just after the search, the Assistant informs the user that the search is in progress and then informs the user that it's completed. It uses two procedure calls—one just before invoking the Execute method and the other just after. Since the FileSearch and Assistant objects depend on the Office Object Library, the procedure calls ReferenceOffice as its first step. If a reference to the Office Object Library does not exist, the procedure creates one. Without this precaution, the procedure would fail if a user inadvertently canceled a reference to the Office Object Library.

Sub FileSearchAct() 'Reference the Office Object Library before using 'either the FileSearch or the Assistant objects. ReferenceOffice 'Search on C drive and its subfolders 'for *.mdb. With Application.FileSearch 'Start a new search. .NewSearch 'Set search criteria. .LookIn = "C:\" .SearchSubFolders = True .FileName = "*.mdb" End With With Application.FileSearch 'Execute the search. 'Turn searching assistant on first. AssistantSearchOn If .Execute() > 0 Then AssistantIdleOn MsgBox "There were " & .FoundFiles.Count & _ " file(s) found." Else 'If no files found, say so. MsgBox "There were no files found." End If End With End Sub

Selecting animation types

The Office Object Library contains over 30 different animation types. Figure 84 shows an Object Browser view that enumerates a subset of the animation types. Most animations, such as msoAnimationSendingMail and msoAnimationPrinting, go through a single cycle and return to idle. Other animations, such as msoAnimationSearching and msoAnimationThinking, repeat until you invoke an alternative animation. Because of IntelliSense, you do not have to recall the constant names for referring to animations. You can often simply select one from a list.

Figure 8-4. The msoAnimationType member of the Office Object Library contains the more than 30 animation constants.

Selecting Assistant characters

Eight Assistant characters ship with Office 2000, but Microsoft might add more in the future. You present an Assistant character by setting its FileName property to the name of that file. The following table lists the Assistant character names and their corresponding files.

Assistant Character Filename
Clippit Clippit.acs
Links OffCat.acs
Rocky Rocky.acs
Office Logo Logo.acs
The Dot Dot.acs
Mother Nature MNature.acs
The Genius Genius.acs
F1 F1.acs

Previewing Assistant animations

Figure 8-5 shows a form in which the assistants act out their animations. The same animation can appear differently from one occurrence to the next. For example, there are at least three different versions of the goodbye animation for the F1 robot. The form offers seven animation types for each of three assistants. You can use the form to preview animations by making a selection from the Animation option group and then clicking an assistant command button. Analyzing the form's code will show you how to incorporate animations and change assistants in your applications.

Figure 8-5. You can use this form to preview the assistant animations.

Figure 8-6 shows a selection of Assistant types and animations that you can preview using the form in Figure 8-5. At the top left, F1, the robot, executes the goodbye animation by burning to oblivion. Clippit rolls up a piece of paper and uses it to portray its searching animation. When Rocky performs the saving to disk animation, it holds up the disk before moving it to a collar pocket for safekeeping. F1 turns into a printer for the printing animation.

Figure 8-6. A selection of animations performed by three different assistants. These were generated with the form shown in Figure 8-5.

The following listing shows the code behind the form in Figure 8-5. The declaration area at the top of the module contains the design-time settings for the command buttons showing the Assistant types, and the buttons for different animation types in the option group. Notice that the buttons store the filename corresponding to the assistant on their face in their Tag property. Each button also has a simple event procedure for its click event. The buttons in the option group each have a value denoting an msoAnimationType constant. You use the Object Browser, shown in Figure 8-4, to determine the numerical value that matches a constant name. (For example, msoAnimationSendingMail equals 25.) As the form loads, it sets a series of properties to ensure that the assistant is ready when the user selects a button in the option group and clicks a command button.

Option Compare Database ' 'Design-time Command button settings ' Name: cmdClippit , cmdRocky, cmdF1 ' Picture: c:\My Documents\My Pictures\clippit.bmp, ' or rocky.bmp, or F1.bmp ' Picture Type: Embedded ' Tag: clippit.acs, or rocky.acs, or F1.acs ' On Click: [Event Procedure] ' 'Design-time Option button settings ' Idle button's Option Value = 1 ' Hello button's Option Value = 2 ' Goodbye button's Option Value = 3 ' Searching button's Option Value = 13 ' Printing button's Option Value = 18 ' Saving Mail button's Option Value = 25 ' Saving to disk button's Option Value = 112 Private Sub Form_Load() With Assistant .On = True .Sounds = True .Visible = True End With End Sub Private Sub cmdClippit_Click() AnimateActor Me.Controls("cmdClippit").Tag End Sub Private Sub cmdRocky_Click() AnimateActor Me.Controls("cmdRocky").Tag End Sub Private Sub cmdF1_Click() AnimateActor Me.Controls("cmdF1").Tag End Sub Sub AnimateActor(Fname As String) With Assistant .FileName = Fname .Animation = _ Me.Controls("optAnimation") .Visible = True End With End Sub

The command buttons are central to the process. When you click a command button, the event procedure passes its tag value to the AnimateActor procedure. This procedure uses its passed argument to set the assistant's FileName property. Next, it sets the assistant's Visible property to True and sets its Animation property to the option group's value. The option group's value is, in turn, a function of the button that you clicked. The control has a default value of 1, in case the user does not make a selection.

Balloons

You can use balloons to present text or graphics as well as to gather feedback from users. You can present balloons as modal, modeless, or autodown dialog boxes. The balloon's Mode property controls the type of balloon. The msoModeAutoDown setting closes the balloon if the user clicks anywhere on the screen. The modeless (msoModeModeless) and modal (msoModeModal) settings are more common. The modeless setting keeps a balloon open while users work outside of it. The modal setting forces a response before allowing any other behavior to occur. The default value for the Mode property is msoModeModal.

You use the NewBalloon property for the Assistant object to create a Balloon object. Balloons have heading, text, label, check box, and button areas. You can populate these areas using corresponding property settings or hierarchical objects such as BalloonCheckBoxes and BalloonLabels. You assign text to the check boxes and labels using their Text property. You can further customize the content of a balloon using its Icon property. Six icons convey various types of message features, such as alerts, questions, information, and tips.

Balloon graphics

The following procedure presents a balloon with a heading, text, and icon. It also uses the default button (OK). Escape formatting strings in the Heading property's text mark the beginning ({ul 1}) and end ({ul 0}) of underlined text in the heading area. (The escape formatting strings can also be used to designate underlined text in the text area.) The Text property setting includes a bitmap image in the text area. Notice that you can wrap text around an image. The Icon property setting marks the balloon's content as information. Finally, the Show method opens the Assistant and its associated balloon. Figure 8-7 shows the Assistant and balloon that appear after you run the balloonTextImageIcon procedure.

Sub balloonTextImageIcon() With Assistant.NewBalloon .Heading = "This is what {ul 1}F1{ul 0} looks like" & _ " in a balloon text area" .Text = " Some text before it " & _ "{bmp ""C:\My Documents\My Pictures\F1.bmp""}" & _ "and more after it." .Icon = msoIconAlertInfo .Show End With End Sub

Figure 8-7. You can include graphics in your balloons, and you can define the content using Icon property settings (such as the AlertInfo icon setting used for this balloon).

Balloon labels

The two procedures prepare a balloon with labels and no buttons. The setLabelCount procedure passes an argument to the balloonHeadTextLabel routine. For valid arguments from 1 through 5, the called procedure presents an assistant with a balloon that contains as many labels as the value passed to it. Each label appears with a simple text string declaring the label number. Buttons in the balloon are not necessary with this design because clicking a label closes the balloon. The Show method opens the balloon and passes the value of the clicked label to the integer variable, i. A message box displays the number of the label the user clicked to close the balloon.

Sub setLabelCount() balloonHeadTextLabel 5 End Sub Sub balloonHeadTextLabel(LabelCount As Integer) On Error GoTo LabelTrap Dim b1 As balloon, i As Integer 'Check for 0 or negative label count. If LabelCount <= 0 Then Err.Raise 9 End If Set b1 = Assistant.NewBalloon 'Create balloon with specified number of labels. With b1 .Heading = "This is my heading" .Text = "Select one of these things:" For i = 1 To LabelCount .Labels(i).Text = "Label " & i Next i .Button = msoButtonSetNone i = .Show End With 'Confirm label that user clicked. MsgBox i, vbInformation, "Programming Microsoft Access 2000" LabelExit: Exit Sub LabelTrap: If Err.Number = 9 Then MsgBox "Number of labels more than 5 or less than " & _ "1. Retry with another number.", vbInformation, _ "Programming Microsoft Access 2000" Else Debug.Print Err.Number MsgBox "Unanticipated error. Error number = " & _ Err.Number & vbCrLf & "Error Description: " & _ Err.Description, vbInformation, _ "Programming Microsoft Access 2000" End If Resume LabelExit End Sub

Built-in and custom error-trapping logic detects illegitimate arguments for the number of labels. If the passed argument is greater than 5, the For…Next loop that assigns label values fails on the attempt to assign text to the sixth label. This error (error number 9) results because balloons can show up to five labels only. Zero and negative arguments to the procedure do not generate the same error, but they also do not populate the balloon with labels. Therefore, the balloonHeadTextLabel procedure traps these values with an If…Then statement and raises a custom error with a number of 9. The procedure's trap for the error instructs the user to enter only values from 1 through 5.

Collecting user input with balloons

The BalloonCheckBoxes collection lets you present a suite of options and collect user responses. You are again limited to five controls—in this case, the controls are check boxes. Unlike label controls, check box controls do not close a balloon after they are selected. Therefore, if you specify a balloon with check boxes, you must assign a button set that can close the balloon.

The two procedures below offer a general framework for displaying check box controls in a balloon. They do not include error trapping, but in practice, you should include error logic like that in the preceding sample. The setCheckCount procedure passes an argument in the range of 1 through 5 to indicate how many check boxes to include. The second procedure starts by setting a reference, b1, to a new balloon. It assigns the Balloon object's Button property to msoButtonSetOkCancel to include OK and Cancel buttons. This offers two routes to closing the balloon. After setting values for the heading and text in the balloon, it assigns text to each text box. The return value from the Show method in this case indicates which button the user clicked.

Sub setCheckCount() balloonHeadTextCheck 5 End Sub Sub balloonHeadTextCheck(CheckCount As Integer) Dim b1 As balloon, i As Integer Dim strChecks As String, iChecks As Integer 'Set reference to the balloon. Set b1 = Assistant.NewBalloon 'Assign text to check box controls. With b1 .Button = msoButtonSetOkCancel .Heading = "Here's the Heading" .Text = "This is some text in the balloon." For i = 1 To CheckCount .Checkboxes(i).Text = "Check box # " & i Next i = .Show End With 'Did user click Cancel button? If i = msoBalloonButtonCancel Then MsgBox "You cancelled the balloon.", vbInformation, _ "Programming Microsoft Access 2000" Exit Sub End If 'Record individual boxes checked and count of 'all checked boxes. For i = 1 To CheckCount If b1.Checkboxes(i).Checked = True Then If strCheck = "" Then strCheck = CStr(i) Else strCheck = strCheck & ", " & CStr(i) End If iChecks = iChecks + 1 End If Next i 'Present a message box with the results. If iChecks = 0 Then MsgBox "No boxes checked.", vbInformation, _ "Programming Microsoft Access 2000" ElseIf iChecks = 1 Then MsgBox "You checked box " & strCheck & ".", _ vbInformation, "Programming Microsoft Access 2000" Else MsgBox "You checked " & iChecks & " boxes. " & _ "These were boxes: " & strCheck & ".", _ vbInformation, "Programming Microsoft Access 2000" End If End Sub

The remainder of the balloonHeadTextCheck procedure processes the reply to the balloon. First, the procedure checks the return value from the Show method. If this value equals the msoBalloonButtonCancel constant, the user clicked the Cancel button. After displaying a message announcing this, the procedure simply exits.

Since the only way to close the balloon is by clicking OK or Cancel, the user must have clicked OK if he or she did not click Cancel. The next block of code performs two tasks: It develops a text string indicating boxes with a check, and then it counts the number of boxes with checks. The last block of code in the procedure uses the string and count to prepare a message box statement that no boxes were checked, only one box was checked, or several boxes were checked.

Modeless balloons

The sample below processes modeless balloons, which stay open while the user does something in another part of the application. All the samples so far have dealt with modal balloons. One feature tailored for working with modeless balloons is the Callback property. You set this property to the name of another procedure that will do something with the response to the balloon. The Callback procedure for a modeless balloon must contain three parameters in a set sequence. The first parameter includes a variable that represents the balloon reference. The second one includes a variable to pass along the control a user clicked. The third one uses a long variable that identifies the Private property of the balloon invoking the callback procedure. It is especially important with a modeless balloon that you designate a control for closing it. If you do not offer the user such a control, the balloon might stay open indefinitely.

The procedure below presents a balloon with four labels. Notice that the balloon's Mode property is msoModeModeless. This setting requires a Callback property setting. Without one, the procedure will generate an error. Notice that one of the labels explicitly denotes a close option. You can also represent a close option using a Button property setting. Clicking a label does not automatically close the balloon; it invokes the Callback procedure named answerHelp. This procedure appears in Figure 8-8.

Sub modalCallbackDemo() Dim b1 As balloon Set b1 = Assistant.NewBalloon With b1 .Heading = "Balloon to Call for Help with a Process" .Text = "Give me more info about:" .Labels(1).Text = "Printing" .Labels(2).Text = "Saving as mail" .Labels(3).Text = "Saving to disk" .Labels(4).Text = "Close" .Button = msoButtonSetNone .Mode = msoModeModeless .Callback = "answerHelp" .Show End With End Sub

Figure 8-8. A modeless balloon and its callback routine.

The answerHelp procedure presents a message box whose content is determined by the label that was clicked in the balloon. The Select Case statement that processes the reply reads the label clicked from the second parameter passed to the callback procedure. After the user closes the message box, the balloon remains open. Generally, users can navigate around a form while a modeless balloon presents help on how to respond to a field on the form. If the user clicks the fourth button, the procedure uses the reference to the balloon, b1, to invoke the Close method.

Категории