Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Create Menus with Macros

Introduction - MS-Access 2003.

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

There are other methods to create simple custom menus for Forms/Reports and use them with your Applications.  We are going to learn how to 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, then click on the Macro-Name Toolbar Button (with xyz label) to display the Macro Name Column.

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

  5. Select Close from the drop-down list of Action.

  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 have selected Employees 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 Action Column.

  19. Save the Macro with the name mcrShortCut and close it.

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

Defining Macro as Menu.

Our work on the Macro Menu is complete, but a little more work is 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 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, this 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 with the name 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 not only create Shortcut Menus but also Toolbars and Menu Bars too.  This we will learn Next.

Share:

Join Split Array Functions-2

Continued from last week's topic.

This is the continuation of last week's Article: Join Split Array Functions

If you have not gone through the fundamentals of the above functions then please do that, by following the above link, before continuing.

Since, Join() and Split() Functions are related, It is time to try out a real-world example with them.  It may not be the easiest solution to the problem we are trying to solve, but it will help to understand these Functions' usage better.

  1. Import Employees Table from the Northwind sample database: C:\Program Files\Microsoft Office\Office11\samples\Northwind.mdb 

  2. Open a new Query in SQL View (don't select any Table from the displayed list).

  3. Copy and paste the following SQL String into the SQL editing window and save the Query with the name EmployeeSelectQ

    .
    SELECT Employees.*
    FROM Employees;
    
  4. Design a new Form like the sample image given below (you may use the Form Wizard to quickly create the Form) using EmployeeSelectQ Query as Record Source. 

  5. Add a Text Box and a Command Button at the bottom of the design.

  6. Select the Text Box and display the Property Sheet (View - ->Properties or Design - ->Property Sheet in 2007).

  7. Change the Name Property Value to txtCodes.

  8. Select the Command Button, change the Name Property value to cmdFilter, and the Caption Property value to Apply Filter.

  9. Select the Child label of the Text Box and change its Caption value to Employee Codes:.

  10. Display the VBA Code Module of the Form (View - ->Code or click the View Code toolbar button from the Design Menu of 2007).

  11. Copy and paste the following VBA Code into the Form Module and save the Form with the name EmployeeSelect:

    Private Sub cmdFilter_Click()
    Dim txt_Codes As String, varList As Variant
    Dim varCodes As Variant, j As Integer, x
    Dim maxCodes As Variant, invalid_Codes As String
    
    txt_Codes = Nz(Me.txtCodes, "")
    maxCodes = DMax("EmployeeID", "Employees")
    
    If Len(txt_Codes) = 0 Then
      varList = Null
    Else
       'Split the items into the array.
      
      '(Here Array() Function will not work
      'becuase the values in txtCodes variable is a String
      'and will be treated as a single item).
    
      varCodes = Split(txt_Codes, ",")
      
      'Validation check
      invalid_Codes = ""
      For j = 0 To UBound(varCodes)
         x = Val(varCodes(j))
         If x < 1 Or x > maxCodes Then
            invalid_Codes = invalid_Codes & Format(x, "0 ")
         End If
      Next
      If Len(invalid_Codes) > 0 Then
         MsgBox "Invalid Employee Codes: " & invalid_Codes & vbCr & vbCr & "Correct and retry."
         Exit Sub
      End If
      'here "varList = txt_Codes" is also works
      'because txt_Codes values are separated with commas already
      varList = Join(varCodes, ",")
    End If
    
      'Call the EmployeeFilter() function
      EmployeeFilter varList
      Me.RecordSource = "EmployeeSelectQ"
      Me.Requery
    
    End Sub
  12. Press Alt+F11 to open the VBA Editing window, if you have already closed it, select Module from Insert Menu to add a new Standard Module.

  13. Copy and paste the following VBA Code of EmployeeFilter() Function into the Standard Module and save it:

    Public Function EmployeeFilter(ByVal Criteria As Variant)
    Dim strsql0 As String, sql As String
    Dim db As Database, qryDef As QueryDef
    
    strsql0 = "SELECT Employees.* FROM Employees WHERE (((Employees.EmployeeID) In ("
    
    Set db = CurrentDb
    Set qryDef = db.QueryDefs("EmployeeSelectQ")
    
    If IsNull(Criteria) Or Len(Criteria) = 0 Then
        sql = "SELECT Employees.* FROM Employees;"
    Else
        Criteria = Criteria & ")));"
        sql = strsql0 & Criteria
    
    End If
        qryDef.SQL = sql
        db.QueryDefs.Refresh
    
    End Function
  14. Open the EmployeeSelect Form in a normal view. The sample image of the Form is given below:

  15. Enter the Employee IDs 2,3,7 and click on the Apply Filter Command Button.

    Now, the EmployeeSelect Form has only three records, with employee codes 2,3 & 7.

  16. Delete all the Text Box contents and click on the Apply Filter Command Button.

The filter action is now reversed and all the records of the Employee Table are now available on the Form.  In other words, it works like a Reset command when the TextBox is empty.

You may try, with some different Employee IDs list.

The values entered into the TextBox must be within the range of the available Employee Code. The numbers entered outside this range will display an Error message and abort the program.

Share:

Join Split Array Functions

Introduction

The Joint/Split MS-Access functions are not so popular or used frequently in programs, but their usage is very interesting and powerful too. Let us take them one by one and learn how powerful they are.  We will write a program later to demonstrate their usage in real-world programs.

Let us take the Array() Function first.  Before we try the Array() Function let us find out how to define an array variable and assign values to each element of the Array.

Demo of Array() Function

'Dimension the array for six elements
Dim varNumber(0 To 5) As Variant, j As Integer
For j = 0 To 5
    varNumber(j) = j + 1
Next
  1. The first statement in the above program defines a variable with the name varNumber, as a Variant Type Array for 6 elements.

  2. Another variable j is defined as an integer type that will be used as an index variable in the For. . .Next loop.

  3. The next three statements in the above program assign values 1 to 6 to the Array elements as:

  • varNumber(0) = 1
  • varNumber(1) = 2
  • varNumber(2) = 3
  • varNumber(3) = 4
  • varNumber(4) = 5
  • varNumber(5) = 6

If we attempt to assign a value to element varNumber(6) then it will run into an error because we have not dimensioned the Array beyond the varNumber(5) element.

We can do this task with only one statement if we use the Array() Function as below:

varNumber = Array(1,2,3,4,5,6)

We don't have to define the variable for a fixed number of elements as we did in the first statement, it does this task automatically depending on the number of items in the argument list.  We have used constant values 1 to 6 to assign to the array elements.  Another thing to keep in mind is that the target variable varNumber must be always defined as a Variant Type Variable.  That gives us more flexibility in assigning mixed Data Type values into different elements of the target variable like the example given below:

    varNumber = Array("Nancy",25,"Andrew",30,172.5)

We have assigned a mix of String, Integer, and Double Data Type values into different elements of the same array.  Again we have used constant values to assign to the array.

This Function is very useful to pass several parameters to a Program as a single block without defining several parameter declarations in the main program.

You can use Constants, Variables, or data Field Values to assign values to the array.

Example-1:

a = "Nancy"
 b = 25
 c = 172.5
 varNumber = Arrary(a,b,c)

Example-2:

varNumber = Array(Me![FirstName],Me![BirthDate],Me![Address])

Next, we will examine the usage of the Join() Function. Let us make another array of values for this function so that its usage is understood easily.

varNumber = Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat")

We have the names of weekdays in the array variable varNumber.

varNumber(0) = "Sun"
 .
 . 
 . 
 varNumber(6) = "Sat"

If you want to combine all values from seven elements of this array variable and create a single string; each item separated with commas (like Sun, Mon, Tue, Wed, Thu, Fri, Sat) then you must write the following statements to achieve this result:

Dim strWeeks as string, j as integer
strWeeks=""
For j = 0 to 6
   if j=6 then
     strWeeks = strWeeks & varNumber(j)
   Else
     strWeeks = strWeeks & varNumber(j) & ","
   end if
Next

Join() Function:

The above task takes only one statement with the Join() Function:

strWeeks = Join(varNumber,",")

The first parameter to the Join() Function is the array of values to be joined together to form a string.  The second parameter is the item separator character; comma, if omitted a space character will be used as a separator character by default, otherwise whatever character you specify will be used as the separator. 

Result: strWeeks = "Sun,Mon,Tue,Wed,Thu,Fri,Sat"

Split() Function:

Split() is the complementary Function of Join().  It splits the individual item separated by the delimiter character and stores the values into an array variable of Variant Type.

We need the following lines of code to do the same task of Split() Function:

Dim strWeeks(0 To 6) As Variant, strtxt As String
Dim j As Integer, k As Integer

strtxt = "Sun,Mon,Tue,Wed,Thu,Fri,Sat"
k = 0
For j = 1 To Len(strtxt) Step 4
   strWeeks(k) = Mid(strtxt, j, 3)
   k = k + 1
Next

With the use of the Split() Function it takes only one statement to do the job that we did with the above program:

 strWeeks = Split(strTxt,",")

Next week we will use these functions in a Program to redefine a Query linked to a Form to filter and view data.

Earlier Post Link References:

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 Class Module External Links Queries Array msaccess reports Accesstips WithEvents msaccess tips Downloads Objects Menus and Toolbars Collection Object MsaccessLinks Process Controls Art Work Property msaccess How Tos Combo Boxes Dictionary Object ListView Control Query VBA msaccessQuery Calculation 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 RaiseEvent Recordset Top Values Variables Wrapper Classes msaccess email progressmeter Access2007 Copy Excel Export Expression Fields Join Methods Microsoft Numbering System Records Security Split SubForm Table Tables Time Difference Utility WScript Workgroup 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 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