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

VBA Module Object and Methods

VBA Module Object and Methods.

The VBA Module Object has several interesting methods and properties.  Last week, we saw how to insert a Click Event Procedure in a Form Module with a Function. You can find this blog post here.

I am not suggesting that the 'frm.Module.CreateEventProc()' method we explored for writing a one-line Event Procedure in a Form Module. However, trying different techniques is always worthwhile because programming is an exploration of new possibilities. After all, this method is available in the Access Application Object Model for us to explore and learn.

Today, we will examine an alternative and simpler approach to the same example we covered last week. Instead of creating the Event Procedure programmatically line by line, we will write the entire procedure in a text file and then load it directly into the Form Module.

If you have already tried last week’s example, we can use the same ‘Sample’ Form for today’s trial run,  or do the following to get prepared:

Loading VBA Code from Text File.

  1. Open a new Form in Design View.

  2. Create a CommandButton on the Detail Section of the Form.

  3. While the CommandButton is selected, display its Property Sheet (F4 or ALT+Enter).

  4. Change the Name Property Value to cmdRun and the Caption Property Value to Run Report.

  5. Save the Form named Sample.

  6. If you have last week’s Sample form, then open it in Design View.

  7. Display the Form Module, remove the existing program lines, and save the Form.

  8. Open Notepad, copy and paste the following program lines into Notepad, and save it as c:\windows\temp\vbaprg.txt

    Private Sub cmdRun_Click()
    
        DoCmd.OpenReport "myReport", acViewPreview
    
    End Sub
  9. Replace the report name "myReport" with one of your own Report Names from the database.

  10. Open a Standard VBA Module, copy and paste the following main program into the Standard Module:

    The LoadFromTextFile() Function.

    Public Function LoadFromTextFile()
    Dim frm As Form, frmName As String, ctrlName As String
    
    frmName = "Sample"
    'ctrlName = "cmdRun"
    
    'Open the form in design view
    DoCmd.OpenForm frmName, acDesign
    
    'define the form object
    Set frm = Forms(frmName)
    
    'call the form's Module Object's AddFromFile() method
    'to read the program from the text file
    'and insert them into the Form Module
    frm.Module.AddFromFile "c:\windows\temp\vbaprg.txt"
    
    'Save and close the form with the code
    DoCmd.Close acForm, frmName, acSaveYes
    
    'Open the form in Normal view
    DoCmd.OpenForm frmName, acNormal
    
    End Function
  11. Place the cursor in the middle of the code, then press F5 to run the Code.

  12. Press ALT+F11 to display the Database window with the Sample Form open.

  13. Click on the Command Button to open the Report in print preview.

  14. Close the Report.

  15. Change the Sample Form in Design View.

  16. Open the form module and check for the program lines we have loaded from the vbaprg.txt File.
Technorati Tags:

Earlier Post Link References:

Share:

Writing VBA-Code with VBA

Writing VBA code with VBA.

To create an Event Procedure in a Form or Report, you can either open the VBA Module and write the procedure manually or open the Class Module through the Event Property of a Control or Form after setting the Event property to [Event Procedure]. When the Class Module is opened in this manner, Microsoft Access automatically inserts the procedure's opening and closing statements (see the example below). You then add the required body of the procedure manually between these generated statements.

A sample empty Subroutine stub of the Form_Current() Event Procedure is shown below:

Private Sub Form_Current()

End Sub

Let us do it differently this time by programming a Command Button Click event procedure through VBA. We will insert a Command Button Click Event Procedure in a Form Module using a Function Write_Code().  We learned something similar through an earlier article on the topic: Creating an Animated Command Button with VBA

A sample Trial Run.

In this trick, the Command Button is programmed automatically to open a Report in Print Preview.  The following are the lines of VBA Code we are going to insert into the Form Module automatically:

Private Sub cmdRun_Click()

    DoCmd.OpenReport "myReport", acViewPreview

End Sub
  1. Open a new blank Form in Design View.

  2. Add a Command Button control on the Form.

  3. While the Command Button is selected, display its Property Sheet (F4 or ALT+Enter).

  4. Change the Name Property Value to cmdRun.

  5. Change the Caption Property Value to Run Report.

  6. Save and close the Form named frmSample.

  7. Open the VBA Editing Window (ALT+F11) and insert a new Standard Module. You can toggle the Database and Code Window with the ALT+F11 Keyboard shortcut.

  8. Copy and paste the following Code into the Standard Module and save it:

    Public Function Write_Code(ByVal frmName As String, ByVal CtrlName As String)
    Dim frm As Form, x, txt As String, ctrl As Control
    
    DoCmd.OpenForm frmName, acDesign, , , , acHidden
    Set frm = Forms(frmName)
    Set ctrl = frm.Controls(CtrlName)
    With ctrl
        If .OnClick = "" Then
           .OnClick = "[Event Procedure]"
        End If
    End With
    
    x = frm.Module.CreateEventProc("Click", ctrl.Name)
    
    txt = "DoCmd.OpenReport " & Chr$(34) & "myReport" & Chr$(34) & ", acViewPreview"
    frm.Module.InsertLines x + 1, txt
    
    DoCmd.Close acForm, frmName, acSaveYes
    DoCmd.OpenForm frmName, acNormal
    
    End Function
  9. Replace the Report name "myReport" with one of your own Report names in the program line: txt = "DoCmd.OpenReport " & Chr$(34) & "myReport" & Chr$(34) & ", acViewPreview".

  10. Display the Debug Window (Ctrl+G).

  11. Type the following line in the Debug Window and press the Enter Key:

    Write_Code "frmSample","cmdRun"

    The Form’s name "frmSample"  is passed as the first parameter to the Write_Code() Function, and the Command Button’s name "cmdRun" is passed as the second parameter.

  12. Press ALT+F11 to display the Database window.  You can see that frmSample is already open in normal view after inserting the program lines in its Code Module.

  13. Click on the Command Button to open your Report in Print Preview with the cmdRun_Click() Event Procedure.  Change the Form View into Design View, open the Form Module, and check the lines of Code we have inserted in there.

At the beginning of the above program, the On Click Event property checks whether a programmed action or Macro name has already been assigned. If the property is empty, it inserts [Event Procedure] into the Property Sheet, preparing it for writing the VBA Event Procedure in the module.

In the next step, the Form Module’s CreateEventProc() method is called to create the Click Event Procedure of the Command Button: cmdRun.  If you want a Double-Click Event procedure, rather than a Click() event procedure, then change the word "Click" to "dblClick".

Replace the 'DoCmd.OpenReport' statement with appropriate Code for other actions like MouseMove.

You can call the Write_Code() function from a Command Button and click Event Procedure on a Form.  Create two TextBoxes on the Form, enter the Form Name and Control Names in them respectively, and use the text box names in both parameters of the Write_Code() function.

Earlier Post Link References:

Share:

Control SetFocus on Tab Page Click

Control SetFocus on Tab Page Click.

A question was raised in an MS Access Discussion Forum:

"When I click on a Tab Control Page, I want to set focus on a particular Text Box on that page, not on the first Text Box by default. How can I do this?"

The user attempted a solution by writing code in the Page2_Click() event procedure of the Tab Control. Specifically, they tried variations of the following lines to set focus on the "Ship City" text box located on that page:

Private Sub Page2_Click()
     Forms!frm_Main![Ship City].SetFocus 
     frm_MainMenu![Ship City].SetFocus 
     me.[Ship City].SetFocus 
End Sub 

Tab Control-based Menus.

The Tab Control is an interesting and versatile object to use on a form. Personally, I have often used it to build form-based menus, placing list boxes on its pages to organize navigation options. For example, the image below shows a sample control screen with list box–based menus arranged neatly on the tab pages.

The middle of the Control Form shows a list as a Menu of choices.  In fact, there are fifteen different sets of menus displayed there.  They are displayed one over the other. Clicking one of the Command Buttons given on either side of the ListBox in the middle displays the related Menu of choices.  You can learn this trick here.

Use the Change Event for the Click Event.

The first thing you should know is that when you click the Tab-Page Button (see the sample image below) on a Tab-Control, the Click Event procedure will not fire; instead, the Change() Event is invoked. So use the Change() Event for Tab Page Clicks.

The Click event of a Tab Control fires only when you click on the top border area to the right of the tab pages. This means you need two clicks: one to select the tab-page button (to display its contents), and another on the Tab Control’s border to trigger the event procedure. Clearly, this is not a convenient approach. Instead, we will take an alternative route that allows the task to be completed with a single click, using the Change event method.

If you have already explored the text links provided earlier, you may have picked up a few ideas—and are probably one step ahead of what I am about to explain here.

Single-Click Solution.

The simple method is the Change Event Procedure on the TabPage Click.

We will implement the following ideas for a different approach:

  1. Create a separate Command Button for each TabPage, with one line of VBA code to make it current or visible.

  2. In the Command Button Click Event Procedure, we will add one more line of code to move the focus to a particular text box in the middle of the tab page.

  3. Since we have Command Buttons to display Tab Pages, we will hide the Tab-Page Buttons of the Tab-control. Optionally, change the Tab-control’s back-style design to transparent to make the tab control’s border design invisible.

Skipping the Fancy Work.

Before diving into the detailed design of the steps mentioned earlier, let me share a very simple solution—if you’re not interested in all the extra work. Simply set the Tab Index property of the text box (for example, [Ship City]) to 0.

Be careful not to confuse the Tab Index with the Tab Control or Tab Page. The Tab Index property determines the order in which the cursor moves from one control (such as a text box, combo box, or check box) to the next when you press the Tab key on the Keyboard.

These values are assigned sequentially, starting from 0 onwards to the number of controls that have the Tab Index property on the form. Access sets these values automatically, based on the order in which you add controls to the form—either manually or through the Form Wizard. When the form opens, the control with Tab Index = 0 receives focus by default, regardless of physical placement on the Form.

So, if the [Ship City] Field is not the starting point on your form and you want to make it so, then do the following:

  1. Open the form in design view.

  2. Click on the [Ship City] field to select it.

  3. Display its Property Sheet (F4 or ALT+Enter).

  4. Find the Tab Index Property and change the Value to 0.  All other controls’ Tab Index Property values will be automatically changed by Access.  You must review and change them to the desired order.

NB:  Each Tab Page is like a separate sub-form and has its own Tab Index sequence numbers starting from zero, even if you place a different group of fields from the current record.

Showing your Professionalism.

Now that you already know the quick and easy solution, let’s explore some advanced tricks for working with Tab Control programming.

Building a database to store and retrieve data is relatively simple—almost anyone can put one together using whatever method they find easiest. That might be fine for personal use, but when presenting a database to a client or end user, appearance and usability matter. A well-designed interface not only improves user experience but also reflects your professionalism and attention to detail.

Returning to our topic, let’s take a closer look at the first three steps of the alternative approach we outlined earlier. For this demonstration, we’ll design a sample form with a Tab Control containing three pages, each holding different groups of information from the Orders table in the Northwind sample database. You can use any table to create a similar form. On the left side of the Tab Control, add three command buttons to support our trial run.

The Design Task

  1. Click on the first Command Button to select it.

    • Display its Property Sheet (F4 or ALT+Enter Keys).

    • Change the Name Property Value to cmdOrder and the Caption Property Value to Order Details.

    • Click the Event Tab Property Sheet, select the OnClick Event property, and select [Event Procedure] from the drop-down control.

    • Click on the Build ( ... ) Button to open the Form’s VBA Module with an empty sub-routine stub.

    • Copy and paste the following lines of Code, overwriting the existing lines, or simply copy the middle line alone and paste it between the sub-routine opening and closing lines, as shown below.

      Private Sub cmdOrder_Click()
        Me.TabCtl0.Pages(0).SetFocus
      End Sub
  2. Similarly, change the middle Command Button’s Name Property Value to cmdShipper and Caption Property Value to Shipper Details.

    • Follow the last three steps mentioned above to copy-paste the following code for the middle Command Button Click Event Procedure:
      Private Sub cmdShipper_Click()
        Me.TabCtl0.Pages(1).SetFocus
        Me.Ship_City.SetFocus
      End Sub

      In the first line of code, we changed the Tab page reference from Page(0) to Page(1), which points to the second page of the Tab Control. We then added one more line:

      Me.Ship_City.SetFocus

      This moves the insertion point directly to the Ship City field, regardless of its physical placement on the form. As a result, a single click on the command button not only switches to the second tab page but also sets the Focus on the Ship City field.

      Notice that we are addressing the control (Me.Ship_City.SetFocus) as though it were placed directly on the form surface, rather than treating it as a child control of the Tab Page. Keep in mind that each group of fields on a Tab Page has its own Tab Index sequence, starting from 0, which determines how the cursor moves among controls on that page.

      If you prefer, you can also reference the control explicitly as a child of the Tab Page, like this:

      Me.TabCtl0.Pages(1).Controls("Ship City").SetFocus

      This approach is equally valid.

  3. Change the last Command Button’s Name Property Value to cmdPayment and Caption Property Value to Payment Details.

    • Copy-paste the following lines of code for the last Command Button Click Event Procedure, as you did in the earlier two cases:
      Private Sub cmdPayment_Click()
         Me.TabCtl0.Pages(2).SetFocus
      End Sub
  4. Save the Form and open it in the normal view. When you open the form, the Tab Page1 will be active.

  5. Click on the middle Command Button. You can see the second page of the Tab Control become active, and the "Ship City" field is in focus.

  6. Click on the Payment Details Command Button to select the third page. You may try all the command buttons repeatedly to understand their usage and responses.

    Since our Command Buttons function as Tab-Pages, we don't need the Tab Control Page buttons above, and we will keep them hidden.

  7. Change the Form Mode in Design View.

  8. Click the Tab Control by clicking on the right side of the Page3 button.

  9. Display the Property Sheet (F4).

  10. Click on the All tab of the Property Sheet and set the Style Property Value to None from the drop-down list.

The Demo Run.

If you open the form in Normal View, the Tab Control will appear as shown in the image below, without the tab page indicators. Clicking the command buttons will still switch the pages, just as before.

You can take this a step further by “hiding” the Tab Control’s identity marks entirely. To do this, set the

The Back-Style property of the Tab Control to Transparent. This creates a clean, seamless interface while retaining full tab functionality—a simple but impressive “magic trick.”

  1. Change the Form to Design View and change the Back Style Property Value to Transparent.

  2. Save the Form and open it in Normal View.

    No sign of the Tab Control now, except for displaying the controls on the first Tab Page with their values and labels. Click the Command Buttons one after the other. You will find that the data fields and their labels appear from nowhere, occupying the same display area every time, like magic.

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