Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

VBA Module Object and Methods

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

I don’t say that the frm.Module.CreateEventProc() method, that we have tried, was an easy approach to write a one line statement in a Form Module.  But, trying something different is always exciting in programming like exploring the unknown.  After all, it is there as part of the Application to explore and learn. 

Today we will try an alternative and simple method for the same example we have tried last week.  That is to write all the program lines in a text file and load that program directly into the Form Module.

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

  1. Open a new Form in Design View.
  2. Create a Command Button on the Detail Section of the Form.
  3. While the Command Button is in selected state display it’s 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 with the name 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 Name from the database.
  10. Open a Standard VBA Module, copy and paste the following main program into the Standard Module:
    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 and 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: ,,
Share:

Writing VBA-Code with VBA

To insert an Event Procedure in a Form or Report we will open the VBA Module and write the code manually.  If we open the Class Module through the Event Property on the Property Sheet of a Control or Form (after setting “[Event Procedure]” value in the Event property) then the procedure’s opening and closing statements (see the example given below) will be inserted by Microsoft Access automatically. After that we insert necessary body lines of the procedure manually between those opening and closing statements.

Sample opening and closing statements of 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 automatically through VBA. We are going to insert a Command Button Click Event Procedure in a Form Module with the help of a Function Write_Code().  We learned something similar through an earlier Article on the topic: Creating Animated Command Button with VBA

In this trick, the Command Button is programmed automatically to open a Report in Print Preview.  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 in selected state display it’s 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 with the name frmSample.
  7. Open VBA Editing Window (ALT+F11) and insert a new Standard Module. You can toggle between Database and VBA Windows with 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 name 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 Enter Key:
    Write_Code "frmSample","cmdRun"

    Form’s name "frmSample"  is passed as first parameter to the Write_Code() Function and Command Button’s name "cmdRun" is as 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 it’s VBA Module.

  13. Click on the Command Button to open your Report in Print Preview with the cmdRun_Click() Event Procedure.  You may 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 OnClick Event Property is checked, for the presence of any programmed action of the Command Button (cmdRun), and inserts the text "[Event Procedure]" in the property in preparation for writing the program lines in the VBA 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 click event procedure on a Form.  Create two Text Boxes on the Form, enter the Form Name and Control Name in them and use the text box names in both parameters of the Write_Code() function.

Share:

Control SetFocus on Tab Page Click

"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 on the Tab page, how?"

The above question was raised in an MS-Access Discussion Forum on the Net.  The user tried a similar set of the sample code given below (with one of the three lines inter-changeably) on the Page2_Click() Event procedure to move the focus to the "Ship City" Field on the tab page, but none of those lines worked, why?:

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

Tab-Control is an interesting piece of Object to use on a Form. I have used this control mainly for building form based Menus with List Boxes on them. You can find a sample image of a Control Screen below with List box based Menus on it:

In the middle of the Control Form shows a list as a menu of choices.  In fact there are fifteen different set of menus displayed there.  They are displayed one over the other by clicking on a set of Command Buttons, shown on either side of the list box.  You can learn this trick from here.

Coming back to the topic, first thing that you should know is that when you click on the Tab-Page Button (see the sample image below) on a Tab-Control the Click Event procedure will not be fired.

This will happen only when you click somewhere on the body of the Tab-Page.  So you need two clicks, one click on the Tab-Page button to make that page contents visible followed by another click on the body of the Tab-Page to run the Page2_Click() Event Procedure so that whatever Code you put in the procedure is executed.  This is not an attractive proposition, but we will take an alternative route to do it with a single-click.

If you have already visited the above text links that I have suggested then you are armed with few ideas and you are already ahead of me on what I am going to say here. 

We will implement the following ideas for a single click solution:

  1. Create separate Command Button for each Tab-Page with one line of VBA Code to make it current or visible.
  2. On the second Command Button click event procedure we will add one more line of code to move the focus to a particular text box at 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 transparent to make the tab control’s border design invisible.

Before going into the detail design of the above steps I can give you a very simple solution, if you are not interested to go into all the fancy work. Set the Tab Index Property Value of the Text box (like [Ship City]) to 0 (zero).

Don’t mix up Tab Index with Tab Control and Tab Page.  When you tap on the Tab-Key on the Keyboard the cursor jumps from one control (Text Box, Combo box, Check-box etc.) to the next based on the Tab Index Property Value setting on those controls.

This value is sequentially numbered from 0 to the number of such controls on a Form.  This is automatically set sequentially in the order in which you place the controls on the form at design time manually or through Form Wizards.  When a Form is open the control with Tab Index value 0 will get focus by default, irrespective of it’s 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 it’s Property Sheet (F4 or ALT+Enter).
  4. Find the Tab Index Property and change the Value to 0.  Other controls’ Tab Index Property values will be automatically changed by Access.  You must review and change them, if needed, to bring them to the desired order.

NB:  Each Tab Page is like a separate sub-form and have separate set of Tab Index sequence numbers starting with zero on them, even if you place different group of fields of the current record.

Now, you are already armed with an easy solution, you may be interested to learn some fancy trick on the Tab Control programming too.

A database can be filled with data very easily.  Any Tom, Dick and Harry can build a database to do that, with whatever easy method available to him.  If it is for his own use then no issues.  But, when it is presented to a Client/User it should have an impressive appearance and should be user-friendly.  Besides that it gives you a chance to advertise your professionalism in your work too.

Coming back to the topic, we will now take the first three steps of action, we have defined above, for a different approach to solve the problem.  A sample design of a Form, with a Tab Control with three pages to hold different group of information from the Orders Table of Northwind.accdb sample database.  You may use any table you like for designing a similar Form, with three Command Buttons at the left side of the Tab Control for trial run:

  1. Click on the first Command Button to select it.
    • Display it’s Property Sheet (F4 or ALT+Enter keys).
    • Change the Name Property Value to cmdOrder and change the Caption property value to Order Details.
    • Click on the Event Tab of the Property  Sheet, select On Click Event property, select [Event Procedure] from the drop-down control.
    • Click on the Build ( . . . ) button to open the Form’s VBA Module with an opening and closing statements of a program.
    • Copy and paste the following lines of Code, over-writing the existing lines, or simply copy the middle line alone and paste it between the opening and closing statements of the program:
      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 code we have changed Tab page reference .Page(0) to .Page(1) that refers to the second page of the Tab Control.  Here we have added one more line Me.Ship_City.SetFocus to move the insertion point (cursor) to the “Ship City” field, wherever it is physically placed.  So, with one click on the Command Button will select the second page of the Tab Control and will set the focus on the Ship City field too.

      We are addressing the control (Me.Ship_City.SetFocus) as if it is directly placed on the form surface rather than as a child control on the Tab Page.  Remember, each group of fields on each Tab Page have separate set of Tab Index sequence numbers starting from 0, to move the cursor around on that page.

      So, if you set the reference of the “Ship City” field as a child control on Tab Page2, like Me.TabCtl0.Pages(1).Controls("Ship City").SetFocus, it 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 for the earlier two cases:
      Private Sub cmdPayment_Click()
         Me.TabCtl0.Pages(2).SetFocus
      End Sub
  4. Save the Form and open it in normal view. When you open the form, by default Page1  of the tab control will be active.
  5. Click on the middle Command Button. You can see the second page of the Tab Control become active and the control "Ship City" field is in focus now.
  6. Click on the Payment Details Command Button to select the third page. You may try all the command buttons repeatedly to get the feel of their usage.

    Since, our command buttons took over the function of Tab-Pages of the Tab Control Object we don't need the Tab Control Page buttons above and we will remove immediately.

  7. Change the Form Mode into Design View.
  8. Click on 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.

    If you open the Form in normal view the Tab Control will look like the image given below, without the Tab Page indicators. Clicking on the Command Buttons will turn the Pages as before. You can do a magic trick by completely hiding the Tab Control's identity marks by setting the Back Style Property Value to Transparent.

  11. Change the form to design view (if the form is in normal view) and change the Back Style Property Value to Transparent.
  12. Save the Form and open it in Normal View.

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

Share:

Translate



PageRank
Your email address:

Delivered by FeedBurner

Search

Infolinks Text Ads


Blogs Directory

Popular Posts

Search This Blog

Blog Archive

Powered by Blogger.

Labels

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

Featured Post

Function Parameter Array Passing

Last week we have explored the usage of ByVal (By Value) and ByRef (By Reference),  in the Function Parameter, to pass the value from  a Va...

Labels

Blog Archive

Recent Posts