Microsoft Access VBA Tutorials for self-paced learning, Class Modules, SQL Techniques, and AI Integration Guides.

Showing posts with label Menus and Toolbars. Show all posts
Showing posts with label Menus and Toolbars. Show all posts

Legacy Custom Menus Toolbars in Access2007

Legacy Custom Menus Toolbars in Access2007.

Custom Menu of Access 2003 in Access 2007.

You may have invested considerable time designing custom menus and toolbars in your MDB database. However, after upgrading to Microsoft Access 2007 and opening your database with the new version, you might notice that the customized menus and toolbars have disappeared.

The Add-In Menu.

Your custom menus and toolbars are not lost—they are still available. In Microsoft Access 2007, they are stored under the Add-Ins tab. Simply click the Add-Ins tab on the Ribbon to find all your custom menus and toolbars there. Refer to the sample image below for guidance.

Have you noticed the group name Custom Toolbars appearing at the bottom of the Add-in Menu?

But the Access 2007 Menu Bars also appear at the top.  You want to turn off the default Access 2007 Menus and Toolbars from the top and replace them with your Custom Menus and Toolbars.


Access Option Changes.

Do the following to get that done:

  1. Click the Office Button (Top-left corner).
  2. Select Access Options.
  3. Select the Current Database.
  4. Move the scroll bar down to find the Ribbon and Toolbar Options as shown in the image given above.
  5. Select your Custom Menu Bar name from the drop-down list, replacing the text (Default).
  6. Select your Shortcut Menu Bar name from the drop-down list, replacing the text (Default).
  7. Remove the check marks from the next three options:
    • Allow Full Menus.
    • Allow Default Shortcut Menu.
    • Allow Built-in Toolbars.
  8. Click OK to save changes to Access Options.

  9. One more step to go:

  10. Close the database and reopen it to register the changes.

Now that the Menu Bars and Tool Bars are in complete control of your Application, they will look like the image given above.

To restore Access 2007 Menus and Toolbars, open the MDB file by holding the Shift key to prevent Auto-Macro from running and to get control of the database window.  Go through Steps 1 to 9 and reverse what you did earlier.

Share:

Create Menus with Macros-2

Create Menus with Macros-2. - Access 2003

Continued from last week’s article: [Create Menus with Macros] – please go through this Article before continuing.

In the previous article, we learned how to create a simple Shortcut Menu for Forms using Macros. This week, we will take this concept further and demonstrate how to create a Toolbar Button and a Menu Bar item using Macro-based menus.

New Macro: macProcess.

But before all that, we need to implement some modifications to our earlier shortcut menu to add a menu group item with a few options.

  1. Open a new macro in the design view.

  2. Select MsgBox from the drop-down list in the Action Column.

  3. Type Proceed with Report Data Processing? In the Message control under the Action Argument list.

  4. Select Critical from the drop-down list in the Type control.

  5. Type Report Processing in the Title control.

    Note: The purpose of this macro is to hold a series of actions, such as running action queries (Make-Table, Append, Update, Delete), executing other macros, or calling VBA routines to prepare data for reports. In this example, we are using a message box to display a sample message. In practice, you should design your menus with actions tailored to specific needs of your application.

  6. Save the Macro named macProcess and close it.

    The macSubMenu Macro.

  7. Click on New to open another macro in Design View.

  8. If the Macro Name Column is not visible, then select Macro Name from the View Menu.

  9. Type &Form in the Macro Name column of the first row and select OpenForm from the drop-down list under the Action Column.

  10. Select an existing Form in the Form Name control using the drop-down control.

  11. Type Process & Data in the Macro Name column in the second row and select RunMacro in the Action Column.

  12. Type macProcess (or select it from the drop-down list) to insert the process macro that we have created in step 6.

  13. Type &Report in the Macro Name column in the third row and select OpenReport in the Action column.

  14. Select an existing Report from your application in the Report Name control.

  15. Select Print Preview in the View control.

  16. Save the macro named macSubMenu and close it.

    Modify Macro: mcrShortCut.

  17. Open the macro mcrShortCut that we created last week.

  18. Type MenuGroup in the next row (as shown in the image given below) and select the AddMenu option from the drop-down list under the Action column.

  19. Type Form/Report in the Menu Name control below the Action Arguments.

  20. Type macSubMenu (or select from the drop-down list) in the Menu Macro Name control.

  21. Save and close the macro mcrShortCut.

  22. If you recall the Form to which you attached the shortcut menu in last week’s exercise, open that form in Normal View and right-click anywhere on it to display the Form/Report submenu we added earlier. If you don’t remember, simply open any of your existing forms in Design View to continue.

  23. Display the Property Sheet (View -> Properties or press ALT+Enter).

  24. Click on the Other Tab.

  25. Set the Shortcut Menu Property value to Yes.

  26. Set the Shortcut Menu Bar Property value to macMenu (you can select the macro from the drop-down list).

  27. Save and close the Form.

    The Shortcut Menu Trial Run.

  28. Open the Form in Normal View.

  29. Right-click on a field to display the Shortcut Menu. The newly added Group Menu will appear at the end of the Menu description Form/Report.

  30. Place the mouse over the Form/Report menu group to display its Sub-Menu items.

The menu definition now remains in Macros, and we are directly using it on Forms.  But we can convert the Menu Macro into a regular:

  • Menu Bar (like File, Edit, etc.) OR
  • Toolbar  OR
  • Shortcut Menu.

If you would like to convert this macro menu into a Menu Bar, then we must make a small change in the macMenu macro.

Converting Macro into Menu Bar.

  1. Open macMenu in design view.

  2. Type myMenu in the Menu Name control under Action Arguments.

  3. Save and close the macro.

  4. Click on the macMenu macro to select it.

  5. Highlight the Macro in the Tools Menu.

  6. Click on the Create Menu from Macro Option.

    A Menu Bar will appear at the top labeled myMenu.

  7. Click on the myMenu option to display the menu options for which we have created macros.

Note: You should not attempt to convert the same macMenu to a Toolbar Menu; a name conflict may take place.

Quick Toolbar Button.

Tip: To create a quick Toolbar Button with the same set of macros, do the following:

  1. Create copies of macros: macMenu, mcrShortCut, and macSubMenu, and rename them to mac_Menu, mcr_ShortCut, and mac_SubMenu.

  2. Open the mcr_ShortCut macro in design view.

  3. Click the last line, change the Menu Macro Name control value to mac_SubMenu, save, and close the Macro.

  4. Open the Mac_Menu macro in design view.

  5. Change the Menu Name control value to myToolbar.

  6. Change the Menu Macro Name control value to mcr_ShortCut, save, and close the Mac_Menu Macro.

  7. Click on the Mac_Menu Macro to select it.

  8. Highlight the Macro in the Tools Menu to display its Options.

  9. Click Create Toolbar from the Macro option to convert the macro into a Toolbar; the myToolbar button will appear near the existing Toolbar label myToolbar.

  10. You may click on it to display the Menu.

Share:

Create Menus with Macros

Create Menus with Macros - MS Access 2003.

We learned earlier how to create Menus and toolbars through the Toolbars -> Customize options.  If you would like to have a second look at them, then the links are given below:

There are other methods for creating simple custom menus for Forms/Reports in your Applications.  This time, we create a Shortcut Menu with Macros and attach it to a Form.

Sample Demo Run.

  1. Select the Macro Tab on the Objects pane.

  2. Click New to open a new Macro in Design View.

  3. If the Macro Name Column is not visible, click the Macro-Name Toolbar Button (the xyz label) that displays the name column.

  4. Type 'Clo&se' under the Macro Name column in the first row.

  5. Select Close from the drop-down list under Actions.

  6. Type &Preview in the second row under Macro Name.

  7. Under Action, select the OpenReport option from the drop-down list.

  8. In the Property Sheet under Action Arguments, select a Report from your list of Reports (I selected the Employees Report in the sample image given above) in the Report Name Property.

  9. Select Print Preview in the View Property.

  10. Type &Form in the third row under the Macro Name column.

  11. Select  Open Form in the Action Column.

  12. Select an existing Form's name from the Form Name Property drop-down list.

  13. Select the Form in the View property.

  14. Type a dash (-) character in the next row under the Macro Name column.

  15. Type &GotoNext in the fifth row under the Macro Name column.

  16. Select GotoRecord in the Action Column.

  17. Type &Minimize in the sixth row under Macro Name.

  18. Select Minimize from the drop-down list in the Action Column.

  19. Save the Macro named mcrShortCut and close it.

You can add as many commands or actions, like opening Queries or running Programs, to your menu for the convenience of your Application Users.

Defining Macro as Menu.

Our work on the Macro Menu is complete, but a few more actions are left to define the Macro as a Menu. 

  1. Open a new macro in the design view.

  2. Select AddMenu from the drop-down list in the Action Column.

  3. Leave the Menu Name Property Blank. This is used for Group Menu Names when you have group Menus with different sets of actions.  In this case, the Macro will have more than one AddMenu Action line with a different set of Menu Macros.

  4. Select mcrShortCut in the Menu Macro Name Property.

  5. Save the macro named mcrShortCutMenu.

  6. Open one of your Forms in Design View (don't open the form that you have used in the OpenForm action in the first macro).

  7. Display the Form's Property Sheet (View -> Properties).

  8. Set the following Property Values of the Form as given below:

    • Shortcut Menu = Yes
    • Shortcut Menu Bar = mcrShortCutMenu
  9. Save the Form.

  10. Open the Form in a normal view.

  11. Right-click on the Form to display the Shortcut Menu.  See the sample image given below:

Try out the options displayed in the Shortcut Menu.

We can create Shortcut Menus, Toolbars, and Menu Bars too.  This we will learn Next.

Share:

Menus with Option Group Control

Menus with Option Group Control.

We can create cascading menus on a form using Tab Controls and Option Group controls. Multiple menus can be arranged neatly, one behind the other, allowing the user to select the main menu option to display the corresponding submenu.

For example, the sample image below illustrates a Main Menu with three options, each representing a different category, along with submenu options for each category.

When the Data Files option is selected in the main menu, the corresponding Submenu appears on the right, allowing the user to click any option to open and work with that file.

Similarly, selecting Reports in the main menu displays the report options in the same area, replacing the previously shown data file options. Choosing the Views option brings up its respective sub-menu, again replacing the previous display.

In this way, multiple menus can be arranged and transitioned in the same space with a seamless, dynamic interface. These menus can be programmed using VBA or macros to run the detailed options associated with each selection.

Simple Interface Design and Code.

You don't need to work with any complicated VBA Programs except a few simple lines of Code and Macros. The design task is simple, and once you know the trick, you can implement it anywhere in no time.

The sample Design image of the above Form is given below:

  1. Open a new Form in the Design view.

  2. Select the Option Group Control from the Toolbox and draw it near the left side of the Form in the Detail Section.

  3. Enter the three Options (Data Files, Reports, and Views), pressing the Tab Key in each step to advance to the next line in the Wizard.

  4. Click Finish to create the Option Group Control with Radio Button Type Controls, with the Keyed-in Values as Labels.

  5. Change the Caption Value of the attached child label to Main Menu and position it above the Options Group control in the design.

  6. Click on the outer frame of the Options Group Control to select it and display its Property Sheet (View -> Properties).

  7. Change the Name Property Value to Frame0 and the Border color Property Value to 0.

  8. Select the Tab Control from the Toolbox and place it to the right of the Options Group Control (check the design image above).

    A Tab Control with two Pages will be created.  We must insert one more Page into the Tab Control.

  9. Right-click on the Tab Control to display the Shortcut Menu.

  10. Select Insert Page from the Shortcut Menu to add another Page to the Tab Control.

  11. While the Tab Control is in the selected state, display its Property Sheet.

  12. Change the Name Property Value to TabCtl9.

    NB: No dot (.) at the end of the name when you change it on the control.

    Data Tables Menu.

  13. Click on the First Page of the Tab Control to make it current.

  14. Select Option Group Control from the Toolbox and draw it on the First Page of the Tab Control.

  15. Enter the following Options (or Form Names of your own Tables in your Database) by pressing the Tab Key after each option on the Wizard:

    • Employees
    • Orders
    • Order Details
    • Customers
    • Products
  16. Click Finish to complete creation of the Option Group with Radio Button Style options.

  17. Display the Options Group Property Sheet (View ->Properties).

  18. Change the following Property Values as shown below:

    • Name = Frame1
    • Default Value = 0
    • Border Color = 0
  19. Change the Caption of the Child-Label attached to the Options Group Control to Data Files.  Change the Label width to the size of the Options Group Control. Position the Label above, as shown in the design image above.

    We must create two Option Group Controls on the 2nd and 3rd Pages of the Tab Control with a different set of Options.

    The Reports Menu.

  20. Follow Steps 13 to 19 to create an Option Group Control on the 2nd Page of the Tab Control with the following options, and name the Option Group Frame as Frame2 and the Child-Label Caption as Report List:

    • Employee Address Book
    • Employee Phone Book
    • Invoice
    • Monthly Report
    • Quarterly Report

    Create Report Names from your own Database, replacing the above List.

    Data View Menu.

  21. Create another Option Group Control on the 3rd Page of the Tab Control with the following options, or create your own Options and name the Option Group as Frame3 and Child-Label Caption as View Options:

    • View Inventory
    • View Orders
    • View Customers
    • View Suppliers

    Now, we have to write a few lines of VBA Code for the Main Menu Option Group to select the detailed Options Page of the Tab Control based on the menu selection. Even though Page Captions show something like Page10, Page11, and Page12, each Page is indexed as 0, 1, and 2. If you want to select the second Page of the Tab Control to display the Report Options, then you must address the Tab Control Page2 in Code as TabCtl9.Pages(1).Setfocus.

    We can select an individual Page of the Tab Control by clicking in the Page.  But this manual action will not synchronize with the Main Menu. The items on the Option Group Menu also have index numbers from 1 to the number of items on the Menu (Report List options 1 to 5).

    When the user selects an item on the Option Group Main Menu, we can test its index number in code and make its corresponding detailed menu on the Tab Control Page current.

    In the final refinement of the Menus, we will hide the Tab Pages of the Tab Control so that the Sub-Menus on them can be accessed only through the program, depending on the selection made on the Main Menu by the User.

    Code for Main Menu.

    First, the On Click Event Procedure of the Frame0 Option Group Control (Main Menu) allows the user to select the options and display their corresponding detailed Sub-Menu on the Tab Control. By default, the 1st item (Data Files) on the Main Menu is selected, and the Data Files list will be visible on the Sub-Menu.

  22. Display the Form Code Module (View -> Code) or click the Module Icon on the Toolbar Button.

  23. Copy and paste the following VBA Code into the Module:

    Private Sub Frame0_Click()
    Dim k
    k = Me![Frame0]
    Select Case k
        Case 1
            Me.TabCtl9.Pages(0).SetFocus
        Case 2
            Me.TabCtl9.Pages(1).SetFocus
        Case 3
            Me.TabCtl9.Pages(2).SetFocus
    End Select
    
    End Sub

    Trial Run of Menu.

  24. Save and close the Form named Main Switchboard.

  25. Open the Main Switchboard in a normal view.

  26. Click the 2nd option, Reports, in the Main Menu to display the Report List on the 2nd Page of the Tab Control.

  27. Try selecting other options on the Main Menu, and monitor the Submenu changes on the Tab Control Pages.

Forms Menu.

Now, we will write VBA Code similar to the above example to open Data File Forms when the User selects Options from the Sub-Menu.

  1. Open the Main Switchboard in Design View.

  2. Display the Code Module of the Form (View ->Code).

  3. Copy and paste the following VBA Code into an empty area of the Module:

    Private Sub Frame1_Click()
    Dim f1
    f1 = Me![Frame1]
    Select Case f1
        Case 1
            DoCmd.OpenForm "Employees", acNormal
        Case 2
            DoCmd.OpenForm "Orders", acNormal
        Case 3
            DoCmd.OpenForm "Order Details", acNormal
        Case 4
            DoCmd.OpenForm "Customers", acNormal
        Case 5
            DoCmd.OpenForm "Products", acNormal
    End Sub
  4. Save and Close the Main Switchboard Form.

    Macros for Report Menu.

    To run the Report Options, we will create a Macro and attach it to the Options Group Control (named Frame2) rather than using the VBA routine.

  5. Select the Macro tab in the Database window and select New to open a new Macro in the design view.

  6. You must display the Condition Column of the Macro by selecting the Toolbar Button with the Icon Image (or similar image) given below:

  7. Write the following Macro lines, as shown in the image given below, with the appropriate Parameter Values at the bottom Property Sheet for opening each Report in Print Preview/Print:

  8. Save the Macro named RptMac.

    Attach the Macro to Report Options.

  9. Open the Main Switchboard Form.

  10. Click on the 2nd Page of the Tab Control to display the Reports Option Group Menu.

  11. Click on the outer frame of the Options Group Menu to select it.

  12. Display the Property Sheet (View ->Properties).

  13. Find and click on the On Click Property to select it.

  14. Click the drop-down list at the right edge of the Property, select the RptMac name in the On-Click Event Property.

     NB: You may create another Macro/VBA Routine for the third menu and attach it to the Frame3 Option Group Menu before doing the next step.

    In the next step, we will remove the pages of the Tab Control. Transitions between tab pages can be controlled entirely through code. This creates a seamless, “magical” effect for the sub-menu, allowing different menus to appear interchangeably in the same location.

    You can further refine the sub-menus by adjusting their dimensions and positions. Ensure you apply the same settings consistently to all three sub-menus on the Tab Control pages for a uniform appearance.

    • Top
    • Left
    • Width
    • height
  15. Click the outer edge of the Tab Control (or click on the right side of the third page) to select it.

  16. Display the Property Sheet (View ->Properties).

  17. Find the Style Property in the Property Sheet and set it to None.

  18. Save and close the Main Switchboard Form.

  19. Open the Form in normal view and try out the Menu.

Share:

Office Assistant And Msgbox Menus-3

After Clickable Menu Options - Access 2003.

After reviewing the earlier articles on this topic, I hope readers are now familiar with the Microsoft Office Assistant Balloon Object for MsgBox. You have seen that with just a few lines of customizable VBA code, you can display message boxes with formatted text—using colors, underlines, and even your favorite images. These balloons can also include menus to capture user responses, in addition to standard buttons like OK, Cancel, Yes, and No.

Since this article is the third part of the series, I recommend that new readers refer to the previous articles to learn these simple techniques in MS Access before continuing. Links to those articles are provided below:

Last week, we learned how to display Clickable Menu Options in a Balloon Object using Office Assistant. The Image of that example is given below.

We have displayed the Menu Options in the Message Box using the Labels Property of the Balloon Object.

Checkbox Menu Options.

In this section, we will learn how to display menu options with checkboxes in a balloon message box and how to capture and process user responses. You will also see how to execute specific actions based on the choices. The example code and a sample image of the message box with the checkbox menu are provided below:

Public Function ChoicesCheckBox()
Dim i As Long, msg As String
Dim bln As Balloon, j As Integer
Dim selected As Integer, checked As Integer

Set bln = Assistant.NewBalloon
With bln
    .Heading = "Select Data Output Option"
    .Checkboxes(1).text = "Print Preview."
    .Checkboxes(2).text = "Export to Excel."
    .Checkboxes(3).text = "Datasheet View."
    .Button = msoButtonSetOkCancel
    .text = "Select one of " & .Checkboxes.Count & " Choices?"
    i = .Show

    selected = 0
    If i = msoBalloonButtonOK Then
        'Validate Selection
        For j = 1 To 3
            If .Checkboxes(j).checked = True Then
                selected = selected + 1
                checked = j
            End If
        Next

       'If User selected more than one item
        'then re-run this program and force the
        'User to select only one item as suggested
        'in the message text.

        If selected = 0 or selected > 1 Then
           Call ChoicesCheckBox
        Else
            Select Case checked
                Case 1
                    Debug.Print .Checkboxes(checked).text
                Case 2
                    Debug.Print .Checkboxes(checked).text
                Case 3
                   Debug.Print .Checkboxes(checked).text
            End Select
        End If
    End If
End With

End Function

Like the Labels Property Array, the dimension of five CheckBoxes only.

In our earlier example, we did not use the OK or Cancel buttons alongside the label-based menu because the Balloon Button (msoBalloonTypeButtons), options were directly clickable. Clicking an item both registered the selection and dismissed the Office Assistant. The index number of the clicked item was returned, making it straightforward to check the selection and execute the corresponding action.

But in the case of check boxes, this is a little more complex because of the following reasons:

  1. The checkboxes can be either checked or unchecked, and their state must be validated. 

  2. The user may select one or multiple options simultaneously. If multiple selections are not allowed, a validation check should enforce the limit of only one item. 

  3. Conversely, if multiple selections are permitted, the program must handle and execute the corresponding actions for each selected option. 

  4. In either scenario, it is essential to inspect the selected state of each element in the CheckBox array to determine the menu selection.

Validating the Checked/Unchecked Items

In the example code given above, the User can select only one item at a time.

  • The first step is to check whether the user clicked the OK button. If she did, the program counts all the check-marked items and stores the total in the variable selected.

  • If selected is zero (the user clicked OK without selecting any option) or greater than one, the ChoicesCheckBox() function is called again. This refreshes the menu, clears any existing check marks, and displays it anew, forcing the user to select a single item or allowing her to click Cancel.

  • Once a valid selection is made, the selected option executes the action corresponding to the user’s choice.

  • If multiple selections are permitted, the validation logic and action execution will differ, and the code must be written accordingly to handle all selected items.

The Balloon Object of the Office Assistant, introduced and explained in these articles, provides a solid foundation for learning the basics of this feature and its various properties.

However, duplicating and customizing this code across multiple programs for different needs is not advisable. Doing so increases the database size, reduces code flexibility, and is generally poor programming practice.

You may refer to the earlier published articles (links provided below), which demonstrate how to define public functions such as MsgOK(), MsgYN(), MsgOKCL(), and others using the Office Assistant. These functions simplify the use of this feature, allowing you to call them anywhere in your programs—just like the standard MsgBox() function—without duplicating code.

The function names themselves indicate the type of buttons that will appear in the message box when called, either with just a message text or with a message text and title.

  1. Message Box using Office-Assistant
  2. Message Box with Options Menu
  3. Office Assistant with CheckBox Menu

For reference, a comparison between the above user-defined functions and the standard MsgBox() function is provided below. Note that the underscore ( ) character is used to indicate line continuation in the code. If you place all values on a single line, the underscore character should not be used.


MS-Access MsgBox() usage Office-Assistant-based User Defined Function usage
MsgBox "Welcome to Tips and Tricks"MsgOK "Welcome to Tips and Tricks"
X = MsgBox("Shut Down Application", vbQuestion+vbDefaultButton2+vbYesNo, _"cmdClose_Click()")X = MsgYN("Shut Down Application", _ "cmdClose_Click()")
X = MsgBox( "Click OK to Proceed or Cancel?", _ vbOKCancel+vbDefaultButton2+vbQuestion, _ "MonthEndProcess()")X = MsgOKCL("Click OK to Proceed or Cancel?", _
"MonthEndProcess()")

Share:

Office Assistant And Msgbox Menus-2

Continued from Last Week. - Access 2003.

This article is a continuation of last week’s post, Office Assistant and MsgBox Menus. If you haven’t read that yet, I recommend going through it first before proceeding with this one.

Last week, we learned how to use the Office Assistant for MsgBox and saw how to create a menu and present it to the User, using the Labels Property of the Balloon Object.


Labels.Text Property

We have seen that we can display the Menu from Labels.Text Properties in three different ways by setting the Values of the Balloon Type Property:

  1. Balloon Type = msoBalloonTypeButtons

    The User can click on any of these buttons to select one of the options presented.

  2. Balloon Type = msoBalloonTypeBullets
  3. Balloon Type = msoBalloonTypeNumbers

The second and third Balloon Type values display the Labels.Text in different visual styles, but they are not interactive—users cannot select them. These types are therefore best suited for situations where you only need to present information, rather than receive user input.

Let’s take a closer look at the Office Assistant's Balloon Object behavior when displaying a Message Box to understand how it works.

If you revisit the earlier examples, you’ll notice that when a message box created with the Office Assistant’s Balloon Object is displayed, you cannot interact with any other objects in the database. You must dismiss the Balloon first by responding to one of its options—such as clicking OK or Cancel—before you can continue.

This behavior is identical to that of the standard MsgBox() function in MS Access. However, the Office Assistant provides ways to overcome this restriction.

When a Balloon is displayed, you cannot, for instance, open a Form or Report to verify some information before clicking Yes or No, because the Mode property of the Balloon Object is set to its default value, msoModeModal.

The Mode Property of Message Balloon

I have not intentionally introduced the Mode property in the earlier examples to avoid overwhelming you with too many details at once. Now that you’re familiar with the basics, it will be easier to understand additional features associated with it.

As you’ve already seen, you can create stylish Message Boxes using the Balloon Object of the Office Assistant with just a few lines of VBA code—without even using this property.

The Mode property can be assigned one of three values, each controlling how the Balloon Object behaves when displayed.

Mode = msoModeModal (default).

This setting forces the user to respond to the Balloon before performing any other action—just like a standard MsgBox in MS Access. The user must click one of the available buttons (such as OK or Cancel) to dismiss the Balloon before continuing with any other task.

Mode = msoModeModeless.

This setting allows the user to access other database objects while the Balloon remains active. However, it also requires another property—Callback—to trigger a separate subroutine that can handle user interactions, evaluate selections or choices, perform the necessary actions, and finally close the Balloon object.

Mode = msoModeAutoDown.

This setting automatically dismisses the Balloon (MsgBox) if you click anywhere else, effectively ignoring it.

The purpose and behavior of the first and last Mode property values are straightforward. However, the second value: msoModeModeless requires special handling. When this mode is used, the Callback property must be set to the name of a valid subroutine; otherwise, the Balloon will fail to function properly. Leaving the Callback property empty (an empty string) will also cause an error.

Let’s now modify our earlier program to demonstrate how to use the Mode property set to msoModeModeless, along with the Callback property, to handle user selections from a menu displayed in the Balloon.

The Mode and Callback Property.

The Modified Code with Mode and CallBack Property Settings and the sample code for the required Subroutine MyProcess() is given below:

Public Sub Choices()
Dim bln As Balloon

Set bln = Assistant.NewBalloon
With bln
    .Heading = "Report Options"
    .Icon = msoIconAlertQuery
    .Button = msoButtonSetNone
    .labels(1).text = "Print Preview."
    .labels(2).text = "Print. "
    .labels(3).text = "Pivot Chart. "
    .BalloonType = msoBalloonTypeButtons
    .text = "Select one of  " & .labels.Count & " Choices? " 
    .mode = msoModeModeless
    .Callback = "myProcess"
    .Show
End With

End Sub

Sub MyProcess(bln As Balloon, lbtn As Long, lPriv As Long)
Assistant.Animation = msoAnimationPrinting
Select Case lbtn
    Case 1
        DoCmd.OpenReport "MyReport", acViewPreview
    Case 2
        DoCmd.OpenReport "MyReport", acViewNormal
    Case 3
        DoCmd.OpenReport "MyReport", acViewPivotChart
End Select
 bln.Close
End Sub

The Callback property is set with the Subroutine name myProcess. When the user clicks on one of the Options from the displayed MsgBox, the MyProcess() Subroutine is called by the Balloon and passes the required Parameter Values.

There are three parameters passed to the Subroutine when called:

  1. The Balloon Object bln.
  2. A Long Integer type value lbtn (BalloonTypeButton) identifying the Option clicked.
  3. A Long Integer type value lPriv (Private) uniquely identifies the Balloon that is called the Sub-Routine, if there is more than one Balloon active in memory at the same time.

NB: There is no such thing as a collection of Balloon Objects. But you can create an Array of Variables with a Balloon Object, define different Property Settings for each of them, and the Show() method is run with their respective index numbers in Programs when you need them to appear.

 lbtn  The variable will have the value of the user's choice. This is tested in the Sub-Routine and runs the  Docmd.OpenReport  action within the Select Case End Select Statements.

The Assistant.Animation = msoAnimationPrinting line is placed in the Subroutine, rather than in the main Program as part of the Balloon Object Property setting, to animate the printing action only after the User makes a selection from the displayed Menu; otherwise, the printing animation will run before the selection of choices.

  bln.close  The statement dismisses the MsgBox.

Next week, we will learn how to use the CheckBoxes.Text Property Values of the Balloon Object to display a Menu with Checkboxes in a MsgBox.

Share:

Office Assistant and MsgBox Menus

Office Assistant and MsgBox Menus - Access 2003.

In last week’s article, Color and Picture in Message Box, we explored several techniques to use the Office Assistant for displaying message boxes with formatted text. In this article, we will move beyond formatting. I believe many readers would now like to learn how this simple feature can be used to gather User responses— allowing them to choose from multiple options and trigger different actions based on their selections.

I have already discussed this concept earlier by creating MsgOK(), MsgYN(), and MsgOKCL() Functions, and others were created using the Office Assistant. These functions can be called from anywhere within your application — just like the built-in MsgBox() function — using only the message text, or both the message text and title as parameters.

My intention in designing these functions was to simplify the Office Assistant’s Balloon object use, which otherwise requires several property values to be manually set for each display.

However, during this simplification process, I’ve found that many readers may not fully understand the underlying method used within these functions.

The Links to those earlier posts are given below for reference:

  1. Message Box with Office Assistant -Access 2003
  2. Message Box with Options Menu - Access 2003
  3. Office Assistant with CheckBox Menu - Access 2003.

In the example code presented in last week’s article, Color and Picture in Message Box, we explored several property values of the Balloon object of the Office Assistant that can be assigned before displaying a message box.

In this session, we will work directly with these properties so that you can clearly understand how each one functions. This approach will make it easier to grasp their behavior and usage, rather than passing values for them indirectly through the parameter list of a function definition.

Message Balloon Properties.

The following are some of these properties:

  • Animation
  • Icon
  • Heading
  • Text
  • Balloon Type
  • Button

Microsoft Office Object Library

Note:
If you have not yet attached the Microsoft Office Object Library to your database, please do so before trying out the examples given here. Follow the steps below:

  1. Press Alt + F11 to open the VBA Code Window (or go to Tools → Macro → Visual Basic Editor).

  2. From the Tools menu, select References.

  3. In the Available References list, locate Microsoft Office Object Library and place a check mark beside it.

  4. Click OK to close the dialog box.

Message Balloon Animation Constants.

The Animation property alone offers about thirty-five different choices, all defined as constants in the Microsoft Office Object Library. For reference, the constant values for the Balloon properties — Animation, Button, Icon, and Balloon Type — are listed below.

Animation Icon

msoAnimationAppear
msoAnimationBeginSpeaking
msoAnimationCharacterSuccessMajor
msoAnimationCheckingSomething
msoAnimationDisappear
msoAnimationEmptyTrash
msoAnimationGestureDown
msoAnimationGestureLeft
msoAnimationGestureRight
msoAnimationGestureUp
msoAnimationGetArtsy
msoAnimationGetAttentionMajor
msoAnimationGetAttentionMinor
msoAnimationGetTechy
msoAnimationGetWizardy
msoAnimationGoodbye
msoAnimationGreeting
msoAnimationIdle
msoAnimationListensToComputer
msoAnimationLookDown
msoAnimationLookDownLeft
msoAnimationLookDownRight
msoAnimationLookLeft
msoAnimationLookRight
msoAnimationLookUp
msoAnimationLookUpLeft
msoAnimationLookUpRight
msoAnimationPrinting
msoAnimationRestPose
msoAnimationSaving
msoAnimationSearching
msoAnimationSendingMail
msoAnimationThinking
msoAnimationWorkingAtSomething
msoAnimationWritingNotingSomething

msoIconAlert
msoIconAlertCritical
msoIconAlertInfo
msoIconAlertQuery
msoIconAlertWarning
msoIconNone
msoIconTip

Button
BalloonType

msoButtonSetAbortRetryIgnore
msoButtonSetBackClose
msoButtonSetBackNextClose
msoButtonSetBackNextSnooze
msoButtonSetCancel
msoButtonSetNextClose
msoButtonSetNone
msoButtonSetOK
msoButtonSetOkCancel
msoButtonSetRetryCancel
msoButtonSetSearchClose
msoButtonSetTipsOptionsClose
msoButtonSetYesAllNoCancel
msoButtonSetYesNo
msoButtonSetYesNoCancel

msoBalloonTypeButtons
msoBalloonTypeBullets
msoBalloonTypeNumbers

The Animation and Icon properties are always set using one of the values listed above, depending on the message you want to convey to the User. By default, the OK button appears. If you need a different button or a group of buttons, then set the Button property values. The Balloon Type property is used in conjunction with the Labels property, which will be covered later in this article.

By going through these simple and straightforward examples, you will gain a better understanding of the Office Assistant, its methods, and how to incorporate them into your Applications.

We will now reproduce the code from last week’s article with minor adjustments and review it before applying changes for our new examples.

Public Sub MyMsgBox()
Dim strMsg As String
Dim strTitle As String

strTitle = "Assistant Test"
strMsg = "Wecome to MS-Access Tips and Tricks"

With Assistant.NewBalloon
    .Icon = msoIconAlertInfo
    .Animation = msoAnimationGetAttentionMajor
    .Heading = strTitle
    .text = strMsg
    .Show
End With

End Sub

Use the Above Code for a Demo Run.

Press Alt+F11 to display the VBA Editing Window. Select the Module option from the Insert Menu to create a new Standard VBA Module. Copy and Paste the above Code into the Module. Click anywhere in the Code and press F5 to run.

The Show() method in the example displays the Message Box after all the other property values have been set. The Text property defines the main body text of the Message Box, while the Heading property sets the title text in bold. The Animation property can be assigned one of the 35 options listed above, and we have set the Icon property to the Information type.

To obtain the User’s response and take different actions accordingly, we need to use the Button property in the code. For example, if the User must proceed to the report preparation process, they would click the OK Button; otherwise, they might click Cancel. We can then evaluate the response from the Balloon Object and write further code in the routine to handle each scenario appropriately.

Modified VBA Code

Let us see how we can do this with changes to the above Code. The modified program is given below:

Public Sub MyMsgBox ()
Dim strMsg As String
Dim strTitle As String
Dim R As Long

Title = "Assistant Test"
msgTxt = "Proceess Weekly Reports...?"

With Assistant.NewBalloon
.Icon = msoIconAlertQuery
    .Animation = msoAnimationGetAttentionMajor 
 .Button = msoButtonSetOkCancel
    .Heading = strTitle
    .text = strMsg 
 R = .Show
End With

If R = -1 Then
'User Clicked OK Button
    DoCmd.RunMacro "ReportProcess"
End If
End Sub

Compare the changes made in the new code with the earlier version to identify the differences.

If the user clicks the OK button (which returns -1 in the variable R; Cancel returns -2 when the Report Process Macro is executed. Otherwise, the program ends without performing any action.

We can also present different choices to the user as a menu using the Labels property and execute actions based on the user’s selection. An example of such code is provided below:

MsgBox-Based Menu Choices.

Public Sub Choices()
Dim R As Long
Dim bln As Balloon

Set bln = Assistant.NewBalloon
With bln
    .Heading = "Report Options"
    .Icon = msoIconAlertQuery
    .Button = msoButtonSetNone
    .labels(1).text = "Print Preview."
    .labels(2).text = "Print."
    .labels(3).text = "Pivot Chart."
    .BalloonType = msoBalloonTypeButtons
    .text = "Select one of " & .labels.Count & " Choices?"
    R = .Show
End With

Select Case R
    Case 1
        DoCmd.OpenReport "MyReport", acViewPreview
    Case 2
        DoCmd.OpenReport "MyReport", acViewNormal
    Case 3
        DoCmd.OpenReport "MyReport", acViewPivotChart
End Select

End Sub 

 Note: You may copy and paste the code into the VBA Module and modify it before attempting to run it.

The Labels() property can hold a maximum of 5 items using the Balloon Type value: msoBalloonTypeButtons. The user can click on one of the options to make a selection. The index of the clicked item is returned in the variable R.

In this example, we set Button = msoButtonSetNone to remove the default OK button, ensuring that the user must select one of the options displayed.

Balloon Type Bullets and Numbers.

Two additional Balloon Type property values are available: msoBalloonTypeBullets and msoBalloonTypeNumbers. Unlike msoBalloonTypeButtons These are not selectable by the user and are intended only for displaying information.

Compare the following Code with the earlier one to see the difference in changed Property Values.

Public Sub InfoDisplay()
Dim bln As Balloon

Set bln = Assistant.NewBalloon
With bln
    .Heading = "Reminder"
    .Icon = msoIconAlertInfo
    .labels(1).text = "MIS Reports."
    .labels(2).text = "Trial Balance."
    .labels(3).text = "Balance Sheet."
    .BalloonType = msoBalloonTypeBullets
    .text = "Monthly Reports for User Departments"
    .Button = msoButtonSetOK
    .Show
End With

Sample Images with Balloon Type Property Changes are given below:

We will continue this discussion next week to explore more ways to use the Office Assistant with Labels and Checkboxes.

Share:

Inputbox and Simple Menus

InputBox and Simple Menus.

We have already learned how to create menus and toolbars through the following articles:

The InputBox() function is one of the first tools we encounter when learning VBA, but it is often discarded later in favor of more “exciting” objects like MsgBox(). This neglect is unfortunate because the InputBox() function is simple to use—just like MsgBox()—and is a useful way to gather user input directly.

While MsgBox() is the more commonly used option and offers a variety of command buttons (OK, Cancel, Retry, Yes, No, etc.), it cannot be programmed to allow selections from user-defined options—a capability that InputBox() provides.

We have also explored how to use the Office Assistant with a preferred animation character as an alternative to MsgBox(), collecting user responses through checkboxes or option balloon menus. Admittedly, the VBA routines involved in these methods are more complex and take some time to fully understand. However, once implemented, these routines are easy to use and freely incorporated into your code across projects—especially if stored in a library database and linked to other projects.

A Simple Example.

Coming back to the InputBox() function, let’s look at a simple example used within a subroutine.

Imagine a Report Command Button on the Main Switchboard: when the user clicks this button, a small menu appears asking whether they would like to:

  1. Preview the Report,

  2. Print the Report directly to the printer, or

  3. Exit, if they change their mind.

The simplest form of the InputBox() function syntax is:

X = InputBox("Message Text", "Title", DefaultValue)
  • Message Text → Appears in the body of the dialog box.

  • Title → Appears in the title bar of the InputBox window.

  • DefaultValue → (Optional) The initial value that appears in the text box.

The Title and Default Value parameters are optional. (There are other optional parameters as well—refer to the Microsoft Access Help documentation for details.)

In our example, we’ll use 1 as the third parameter (Default Value). This means that when the InputBox appears, the value 1 will already be displayed in the text box, as shown in the example image below.

The Code that brings this Form up with a Command Button Click Event Procedure is given below.

Private Sub cmdRpt_Click()
Dim varResponse as Variant

varResponse = InputBox("(1) Print Preview (2) Print (3) Exit", "Select 1/2/3",1)

Select Case varResponse
    Case 1
        DoCmd.OpenReport "Orders", acViewPreview
    Case 2
        DoCmd.OpenReport "Orders", acViewNormal
    Case 3
        Exit Sub
End Select

End Sub

When the user makes a selection from the options provided, the chosen value is evaluated using the Select Case... End Select statement, and the corresponding action is executed.

Note:
The InputBox() function displays a small form whose Border Style property is set to Dialog. As a result, the Minimize, Maximize, and Restore buttons are removed from the title bar, leaving only the Close button.

Additionally, while the InputBox is open, you cannot click on any other form or object within the Access application window. This behavior indicates that the InputBox operates with its Modal property set to Yes—it must be closed or completed before returning control to the other parts of the application.

We have already explored the usage of Pop-up, Modal, and other related form properties in our earlier discussions on Form design and behavior, particularly in the following articles:

Taking Care of Pitfalls

While using the InputBox() function this way in programs, we must take care to avoid a few undesirable side effects and also pay attention to improving the appearance of the menu.

Let us first deal with the side effects. We have provided Option 3 to close the dialog box normally if the user changes her mind after opening the menu. However, she might ignore Option 3 and instead use the Close button on the title bar or click Cancel, and that can cause problems in the code.

Since the option values in the menu are defined as integers (1, 2, and 3), it is natural to use an Integer variable to capture the user’s response. But if the user closes the window using the Cancel button or the Close control, the InputBox() function returns an empty string (""). If this value is assigned to an Integer variable, a Type Mismatch error will occur, and the program will crash.

To avoid this, we can declare the variable as a String, which can safely receive an empty string. The Select Case... End Select structure will still work correctly even though we are testing for numeric values, because VBA automatically handles the type conversion in this context. A better alternative, however, is to use a Variant variable, which can accept any data type and gives more flexibility.

With a small trick, we can also make the program ignore Cancel and Close button clicks, forcing the user to choose one of the defined menu options if she wants to exit the menu normally.

We have inserted 1 as the third optional parameter value in the InputBox() function to handle the case where the user clicks OK without entering anything in the TextBox. If she types one of the option values and presses Enter, as expected, that value will be returned into the varResponse variable, and the InputBox() will close normally.

We will modify the above Code:

  1. To make a real Menu with a good appearance.

  2. To ignore the Cancel Command Button and Window Close Title Bar control clicks.

  3. To prepare the Menu, we will define a string Variable and write the following expression before inserting it into the InputBox() Function:

    Dim strMenu as String
    
        strMenu = "1. Report Preview" & vbCr & vbCr
    
        strMenu = strMenu & "2. Print Report" & vbCr & vbCr
    
        strMenu = strMenu & "3. Exit"
          
  4. We will place the InputBox() function inside a Do While...Loop structure. This ensures that the menu keeps reappearing until the user makes a valid selection from the available options. In this setup, the user will not be able to exit the dialog box by clicking the Cancel button or the Close control on the title bar. The loop will continue to prompt the user until a valid response—such as 1, 2, or 3—is entered.

varResponse = ""
Do While Len(varResponse) = 0 Or varResponse < 1 Or varResponse > 3

       varResponse = InputBox(strMenu, "Select 1/2/3",1)

  Loop

After the above changes, the Menu will look like the following image:


Modified VBA Code

The modified code is given below:
Private Sub cmdRpt_Click()
'------------------------------------------------------------
'Author : a.p.r. pillai
'Date : March-2009
'URL  : www.msaccesstips.com
'All Rights Reserved by www.msaccesstips.com
'------------------------------------------------------------
Dim varResponse As Variant
Dim strMenu As String

strMenu = "1. Report Preview" & vbCr & vbCrstrMenu = strMenu & "2. Print Report" & vbCr & vbCrstrMenu = strMenu & "3. Exit"

varResponse = ""
Do While Len(varResponse) = 0 Or varResponse < 1 Or varResponse > 3
    varResponse = InputBox(strMenu, "Select 1/2/3", 1)
Loop

Select Case varResponse
    Case 1
        DoCmd.OpenReport "Orders", acViewPreview
    Case 2
        DoCmd.OpenReport "Orders", acViewNormal
    Case 3
        Exit Sub
End Select

End Sub

Probably the next question that comes into one's mind is, do we have to use the Menu Options always in the form 1,2,3, etc., or can we use letters instead, like

  • R. Report Preview
  • P. Print Report
  • E. Exit?

Yes, we can with a few changes in the Code as given below:

strMenu = "R. Report Preview" & vbCr & vbCr
strMenu = strMenu & "P. Print Report" & vbCr & vbCr

strMenu = strMenu & "E. Exit"

varResponse= ""

Do While instr(1, "RPE",varResponse)=0 or len(varResponse)=0
    varResponse = InputBox(strMenu, "Select R/P/E", "R")

Loop

The Select Case... End Select statements must be changed to:

Select Case varResponse
  Case "R"

      DoCmd.OpenReport "Orders", acViewPreview

  Case "P"

      DoCmd.OpenReport "Orders", acViewNormal

  Case "E"

      Exit Sub

End Select

Option Alphabet Values

The changed Code with alphabet as Options is given below:

Private Sub cmdRpt_Click()
'------------------------------------------------------------
'Author : a.p.r. pillai
'Date : March-2009
'URL  : www.msaccesstips.com
'All Rights Reserved by www.msaccesstips.com
'------------------------------------------------------------
Dim varResponse As VariantDim strMenu As String

strMenu = "R. Report Preview" & vbCr & vbCr
strMenu = strMenu & "P. Print Report" & vbCr & vbCr
strMenu = strMenu & "E. Exit"

varResponse = ""

Do While InStr(1, "RPE", varResponse) = 0 Or Len(varResponse) = 0
    varResponse = InputBox(strMenu, "Select R/P/E", "R")
Loop

Select Case varResponse
    Case "R"
        DoCmd.OpenReport "Orders", acViewPreview
    Case "P"
        DoCmd.OpenReport "Orders", acViewNormal
    Case "E"
        Exit Sub
End Select

End Sub
Share:

PRESENTATION: ACCESS USER GROUPS (EUROPE)

Translate

PageRank

Post Feed


Search

Popular Posts

Blog Archive

Powered by Blogger.

Labels

Forms Functions How Tos MS-Access Security Reports msaccess forms Animations msaccess animation Utilities msaccess controls Access and Internet MS-Access Scurity MS-Access and Internet External Links Queries Array Class Module msaccess reports Accesstips msaccess tips WithEvents Downloads Objects Menus and Toolbars MsaccessLinks Process Controls Art Work Collection Object Property msaccess How Tos Combo Boxes ListView Control Query VBA msaccessQuery Calculation Dictionary Object Event Graph Charts ImageList Control List Boxes TreeView Control Command Buttons Controls Data Emails and Alerts Form Custom Functions Custom Wizards DOS Commands Data Type Key Object Reference ms-access functions msaccess functions msaccess graphs msaccess reporttricks Command Button Report msaccess menus msaccessprocess security advanced Access Security Add Auto-Number Field Type Form Instances ImageList Item Macros Menus Nodes Recordset Top Values Variables msaccess email progressmeter Access2007 Copy Excel Expression Fields Join Methods Microsoft Numbering System RaiseEvent Records Security Split SubForm Table Tables Time Difference Utility WScript Workgroup Wrapper Classes database function msaccess wizards tutorial Access Emails and Alerts Access Fields Access How Tos Access Mail Merge Access2003 Accounting Year Action Animation Attachment Binary Numbers Bookmarks Budgeting ChDir Color Palette Common Controls Conditional Formatting Data Filtering Database Records Defining Pages Desktop Shortcuts Diagram Disk Dynamic Lookup Error Handler Export External Filter Formatting Groups Hexadecimal Numbers Import Labels List Logo Macro Mail Merge Main Form Memo Message Box Monitoring Octal Numbers Operating System Paste Primary-Key Product Rank Reading Remove Rich Text Sequence SetFocus Summary Tab-Page Union Query User Users Water-Mark Word automatically commands hyperlinks iSeries Date iif ms-access msaccess msaccess alerts pdf files reference restore switch text toolbar updating upload vba code