Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Embedded Macros in Access2007

Introduction.

There is only one difference between the stand-alone Macros and embedded macro; they will not appear in the navigation pane under the Macros Group.  They are written directly on Forms/Reports or on their control's event property.  When you make a copy of the Form or Report the embedded macros to go along with it.

Let us try and find out how embedded macros are created.

Creating Embedded Macros.

  1. Open Microsoft Access2007.

  2. Open a Report in Design View.

  3. Press F4 or Alt+Enter to display the Property Sheet of the Report.

  4. Click on the Event Tab of the Property Sheet.

  5. Click on the On Load Event Property to select it.

  6. Click on the Build (. . .) button on the right side of the property.

  7. The Macro Builder option is already in the selected state, Click OK Command Button to accept it.

    The Macro is open in Design View.  The title bar of the macro indicates Catalog:Report: On Load (the Report Name: Object Type: Event Type) where the macro will be embedded. 

  8. Select MsgBox Action and type my Embedded Macro in the Message Action Argument.

  9. Type On Load Info in the Title Argument of MsgBox Action.

  10. Click on the Close Toolbar button to save and close the Macro.

  11. Save and Close the Report.

  12. Right-Click on the Report in the navigation pane and select Open to open the Report in Report View.  The embedded macro will run and you will see the message.

  13. You can modify the macro by following steps 2 to 6.  You can add several actions in the Macro if needed.

Share:

Report Design in Access2007

Introduction.

In Microsoft Access 2007 there are some interesting design-time features; Report View (not Print Preview) and Layout View besides Design View and Print Preview. These two new views allow working with the report interactively.  In earlier versions of Access, we had only Design View and Print Preview options.

Report View looks almost like Print Preview but with lots of differences. You can search for data on the Report, Copy data from the report into the Clipboard, Filter Records, and find out summary values of the filtered records. If you want to retain the filtered records and show them when you open the Report you can do that by setting the Filter on the Load property value to Yes.

Layout View is somewhat like Design View in that you can rearrange the fields while viewing the report contents, add or remove fields, increase or decrease field sizes or set data field property values to reflect changes in the report data.


The Report View Feature.

  1. Let us try out the above features; open Microsoft Access 2007.

  2. Open one of your Databases.

  3. Import the Order Details Table from the Northwind.mdb sample database.

  4. Click on the Table to select it.

  5. Click on the Report Option from Create a Menu to create a Report with the basic design and save it with the name Order Details.

  6. Right-Click on the Order Details Report in the navigation pane and click on the Open option to open the Report in Report View.

Now, let us try search, filter, and copy operations in the Report View mode.

  1. Click on the OrderID field in the first record on the Report to select it.

  2. Click on the Find Toolbar button (the field-glass icon) under the Home menu.

  3. Type 10251 in the Find What: control and click on the Find Next Command Button.  The first record with OrderID number 10251 is highlighted.  You can repeat the search operation by clicking on the Find Next Command Button.

  4. Let us do some filter action; click on the Cancel to cancel the Find operation and close the dialog box.

  5. Click on the Filter Toolbar Button.  The following filter control will be displayed over the report.

  6. Click on the Select All option to remove all the check-marks.

  7. Put check-marks on OrderID Numbers 10251 and 10255.

  8. Click the OK Command Button to filter records with the selected OrderIDs on the Report.

  9. You can click on the Toggle Filter Toolbar button to display all the records or filter the records again.

To copy selected records from the Report to the Clipboard:

  1. Click on the left border of the topmost record on the report and drag it down to highlight a few records to select them.

  2. Click on the Copy toolbar button under Home Menu to copy the highlighted records onto the Clipboard.  These records you can paste into Excel, Word, etc.

If you want to see the same set of filtered records every time you open the Report then you must change the Property Value of the Report.

  1. Select the Design View option from the View Menu.

  2. Select the Property Sheet option to display the Property Sheet of the Report.

  3. Click on the Data Tab of the Property Sheet.

  4. Set the Filter on the Load property value to Yes.

  5. You can add or remove OrderID numbers in the IN clause of the Filter condition in the Filter property value if needed.

  6. Save the changes and close the Report.

  7. Open the Report in Print Preview and check whether the filter action is in effect or not.

  8. Close the Report.

The Layout View Feature.

Now, it is time to try out the Layout View options.

  1. Right-click on the Order Details Report in the navigation pane.

  2. Select Layout View from the displayed shortcut menu.

  3. Click and hold on the OrderID heading, and drag and drop it after the Discount Column.  You can not only do this with the column header but also on any row of records.

  4. Click on any row in the Discount column to select the column.

  5. Press the delete key to remove the column from the Report.

    Let us try to bring that column back into the Report from the Field List of the Source Table.

  6. Click on the Add Existing Fields Toolbar Button from the Format Menu.

  7. Drag the Discount Field and drop it between Unit Price and OrderID fields.

  8. While the Discount Field is still in the selected state, click on the Arrange Menu to display its Toolbar.

  9. Click on the Property Sheet Tool to display the Property Sheet of Discount Field.

  10. Click on the Format Tab of the Property Sheet.

  11. Change the Decimal Places property value to 2 and change the Width Property value from 1 inch to 0.75 inches.

The interactivity feature is very powerful in the process of designing Microsoft Access Reports and makes the design task easier and more interesting too.

Technorati Tags:
Share:

Memo Field Text Formatting

Introduction.

We know that Memo Fields in Microsoft Access Tables give us much-needed flexibility to record variable length Text data.  But, Access Versions earlier than 2007 allows us to enter in plain text format only like we do in Notepad.

The need for some form of text formatting was always felt necessary to organize them in the form of a Numbered List or Bullet List or highlight text to draw attention to important points etc. 

Well, the waiting is over and here it is in Microsoft Access2007.

A Sample Quick Run.

Let us quickly try and find out how it works.

  1. Open Microsoft Access2007

  2. If you have an earlier MS-Access Version Northwind.mdb sample database, then open it, otherwise select Sample from the displayed list of Templates, and click on the Northwind 2007 Template.

    • Click on the Folder Icon on the right side to select the folder to save the Northwind 2007.accdb file and click on the Create Command Button to create and open the file.
    • Click on the Login Command Button

    • Close the Home Form.

  3. Open the Employees Table in Design View.

  4. Click on the Notes Field to select it.

  5. Click on the Text Format Property on the General Tab of the Field Properties Sheet.  The current value of the Property is Plain Text.

  6. Select Rich Text from the drop-down list to replace Plain Text.

  7. You will see a warning message below; click Yes to apply the change.

  8. Close the Design View and save the changes.

  9. Open the Employees Table in Datasheet View.

  10. Expand the Row Height of the records by dragging the intersection of the two records at the left border.

  11. Bring the Notes Field values into view by moving the Scrollbar to the right and increasing the column width, see the image below.

  12. You can now format the Memo Field Text as you apply Text formatting in MS Word.

  13. In the example image above, I have created a Numbered List, Bullet Text, applied Bold, Italics, highlighting, alternate rows fill/back color, etc.

Share:

Sub-Query in Query Column Expressions

Introduction

Queries are the main data processing component of the database systems.  Queries work behind the scene shaping the data into Reports and other forms of outputs.  Microsoft Access Users (mostly beginners) attempt to create the output for a Report, by chaining several Tables in Queries together and the report data are expected to form in one or two query steps.  This approach may not be the correct one because it will be difficult to get the proper output for the Report.

First, you must plan your Report by defining the layout, contents, grouping, summary, etc.  If several related tables are involved in organizing the required data then you may take smaller steps of joining a few tables or queries together in a Query.  Use this Query as input and combine it with other tables in the next step.  You may create intermediate tables and create Queries out of them for further processing of information.  In these steps, you may use Make-table, Append Table, Update, etc., to process the data.

When Report Requirement is Complicated.

When the Report contents are complicated and difficult to create in one go then my approach is to create a Report table and bring the data piece by piece from the source Table(s) with Queries/VBA Routines and add or update them into the Report Table before opening the Report.  These processing steps can be automated through Macros/VBA.

Necessary report parameters like date-range or filtering criteria values will be collected in a parameter table to use in data processing queries.  There will be options in the Parameter Form either to Re-run the Report creation procedure with changing parameter values or to open the existing Report in Preview/Print mode. 

Using Sub-Query in Criteria Row.

Here, we are trying to explore the usage of Sub-Queries in the Queries to filter or incorporate data from tables or from other Queries.

Let us look at a simple Query that uses a sub-query in the criteria section to filter data from the Orders Table.   In the Orders table, there are about 830 Orders ranging OrderIDs from 10248 to 11077.  We need to filter certain Groups of Order (say Order Numbers 10248,10254,10260,10263,10267,10272,10283) for review.

Following is an SQL of a sample Query that filters the above Orders without the use of a Sub-Query:

SELECT Orders.*
FROM Orders
WHERE (((Orders.OrderID) In (10248,10254,10260,10263,10267,10272,10283)));

The above Query does the job, but the problem is when we want a different set of Orders to be filtered then the Query's Criteria line needs to be modified physically to replace with a new set of Order Numbers to filter.  We cannot expect the User to do this task manually, instead, we must provide them with an option to key in the Order Numbers into a table (ParamTable with a single field: OrderNumber) and use it as criteria.  This method will facilitate the automatic detection of the change of values in the table at run time.  The User can simply type the Order Numbers in a Datasheet Form and click a Command Button to run the query with the changed order numbers.  With this method, we need a Sub-Query in the criteria row to compare the Order Numbers in the Paramtable with the Order Numbers in the Orders Table and filter data.

We will modify the Query to insert a Sub-Query in the Criteria Row to pull the values from the ParamTable and to use the OrderNumber field values as criteria. 

The modified SQL String of the Query is given below:

SELECT Orders.*
FROM Orders
WHERE (((Orders.OrderID) In (SELECT OrderNumber FROM OrderParam)));

The Sub-Query string in the Criteria Row is in Bold in the SQL above.

Sub_Query in a Query Column.

It is likely that you already came across the above sub-query before, but we are going to learn how to use a Sub-Query as an expression in a Query Column to incorporate values from a different table, related to the Query Source Table. This usage is not so common and it is very useful in difficult times.

When several tables are used in a Query with LEFT JOIN or RIGHT JOIN relationships it becomes difficult to link all the related tables this way to incorporate summary values of one table. This is more so when one-to-many relationships are involved.

We will use Orders and Order Details Tables from the Northwind.mdb sample database for our example. Import both these tables from the Northwind.mdb sample database from C:\Program Files\Microsoft Office\Office11\Samples\Northwind.mdb.

The sample Query (in normal style), given below, uses both the Tables in the Query, linked to the OrderID Field of both tables to create an Order-wise Summary from the Order Details Table.

SELECT Orders.OrderID,
 Orders.CustomerID,
 Sum((1-[Discount])*[UnitPrice]*[Quantity]) AS OrderVal
FROM Orders INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID
GROUP BY Orders.OrderID, Orders.CustomerID;

The same result can be achieved without placing the Order Details Table in the Query design. We will write an expression in a separate Column using a Sub-Query to pull the summary Order-wise Total Value directly from the Order Details Table. Here is the example SQL String:

SELECT Orders.*,
    (SELECT  Sum((1-[Discount])*[UnitPrice]*[Quantity]) AS OrderValue
     FROM [Order Details] AS ODetails WHERE ([ODetails].[OrderID] = [Orders].[OrderID])
GROUP BY [ODetails].OrderID) AS OrderVal, [OrderVal]*0.12 AS Tax
FROM Orders;

There are several records in the Order Details table for a single order in the Orders Table.  Through the Sub-Query (Total Query) we sum up the Sale Value of each Order and places the result in its corresponding row in the output.  So, the Sub-Query runs in a separate Column as an expression independently for each row in the Orders table for the output.

The new column name: OrderValue created can be part of other expressions and we have calculated the Tax value 12% of Order Value, in a separate column.

Let us take a closer look at the Sub-Query.

  1. The SELECT clause uses only one output column (Sum((1-[Discount])*[UnitPrice]*[Quantity]) AS OrderValue) and the expression is named as OrderValue.  You should not use more than one column in the SELECT clause.
  2. In the FROM clause, the Order Details Table is given a new name (ODetails) and this name is used to qualify the OrderID field in the WHERE clause.  The OrderID field appears in both Orders and Order Details Tables.
  3. The WHERE clause in the Sub-Query is necessary to match the OrderIDs of both tables and place the calculated values in their matching row of Order Records.

Earlier Post Link References:

Share:

GetRows Function and Exporting Data

Introduction

We are going to create a useful data export utility with the GetRows() method of the Recordset Object. The GetRows method is used for loading the entire set of data from the table into memory in a doubly dimensioned Variant Array with a single statement. Let us try it with an example to see how this is done. An image of a sample table is given below and we will see how this will look like in memory when loaded with the help of the GetRows() method of the Recordset Object:

Table: Employees
ID Name BirthDate Height Weight
1 Nancy 12/10/1980 164 58
2 Peter 05/07/1975 180 80
3 Linda 17/11/1982 170 60

The VBA Code.

The following sample VBA Routine loads the above data into memory and a listing is dumped in the Debug Window:

Public Function Test(ByVal tblName As String)
Dim db As Database, rst As Recordset, varData As Variant
Dim intFields As Integer, intRecords As Integer, j As Integer, k As Integer
Dim rec As String, fld_type As Integer

Set db = CurrentDb
Set rst = db.OpenRecordset(tblName, dbOpenTable)
j = rst.RecordCount - 1
k = rst.Fields.Count - 1

varData = rst.GetRows(j + 1)

For intRecords = 0 To j
    rec = ""
    For intFields = 0 To k
    fld_type = rst.Fields(intFields).Type

    If fld_type = 11 Or fld_type = 12 Then
      GoTo nextField
    End If
      rec = rec & varData(intFields, intRecords) & ","
nextField:
    Next
    rec = Left(rec, Len(rec) - 1)
    Debug.Print rec
Next
rst.Close
Set rst = Nothing
Set db = Nothing
End Function

The arrangement of records in memory in a two-dimensional array looks like the following:

1 2 3
Nancy Peter Linda
12/10/1980 05/07/1975 17/11/1982
164 180 170
58 80 60

The Memory Image of the Data.

The records are not arranged in row order as they appear in the datasheet view, they are loaded in columns instead.  So, after loading the data in memory we must know how to address the two-dimensional array to access each record in the correct order to output the data.  Each field value is separated with a comma in the listing provided in the Debug window.

Normally, in a two-dimensional array, the first index value of the array is the row number and the second one is the column number.  But, in this case, the first index value is the Field order Number and the second value is the Record Number.  You can check the sample data arrangement in the memory shown above.

Export Data in Text Format

We will write a small utility program to export any MS-Access Table into a comma-delimited Text/CSV File, so that the data can be easily transported through the internet or to import into other applications.

The VBA code of the program is given below:

Public Function CreateDelimited(ByVal xtableName As String, ByVal txtFilePath As String)
'-----------------------------------------------------
'Utility: CreateDelimited()
'Author : a.p.r.pillai
'Date   : Dec. 2010
'Purpose: Create Comma Delimited Text File from Table 
'Rights : All Rights Reserved by www.msaccesstips.com
'-----------------------------------------------------
Dim db As Database, rst As Recordset
Dim varTable() As Variant, j As Long, k As Long
Dim rec As String, fld_type As Integer
Dim intRecords As Integer, intFields As Integer

Set db = CurrentDb
Set rst = db.OpenRecordset(xtableName, dbOpenTable)
varTable = rst.GetRows(rst.RecordCount)
k = rst.Fields.Count - 1
j = rst.RecordCount - 1

Open txtFilePath For Output As #1
rec = ""
For intFields = 0 To k
   fld_type = rst.Fields(intFields).Type
        If fld_type = 11 Or fld_type = 12 Then GoTo nextField
   rec = rec & Chr$(34) & rst.Fields(intFields).Name & Chr$(34) & ","
nextField:
Next
rec = Left(rec, Len(rec) - 1)
Print #1, rec
For intRecords = 0 To j
    rec = ""
    For intFields = 0 To k
        fld_type = rst.Fields(intFields).Type
        If fld_type = 11 Or fld_type = 12 Then GoTo Next_Field
        rec = rec & IIf(fld_type = 10, Chr$(34) & varTable(intFields, intRecords) & Chr$(34), varTable(intFields, intRecords)) & ","
Next_Field:
        Next: rec = Left(rec, Len(rec) - 1)
        Print #1, rec
Next
Close #1
rst.Close

Set rst = Nothing
Set db = Nothing

End Function

The Utility can be called from a Command Button Click Event procedure after setting the Table name and the target file pathname in text boxes.  You can test the utility by calling it from the Debug Window (Immediate Window) directly as given below:

CreateDelimited "Products", "C:\Temp\Products.txt"

NB: If MEMO or Photo Fields are present in the Table they are excluded from the output file.

The target file extension can be either .TXT or .CSV.

Earlier Post Link References:

Share:

Create Menus with Macros-2

Continued from Create Menus with Macros. - Access 2003

Continued from last week's Article: Create Menus with Macros, please go through it before continuing.

Last week we learned how to create a simple Shortcut Menu for Forms with Macros.  This week we will create a Toolbar Button and a Menu Bar item through Macro-based Menus.

New Macro: macProcess.

But, before all that, let us make a little modification to our earlier shortcut menu to add a menu group item added 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: This macro is supposed to contain a series of actions; like running action queries (Make-Table, Append, Update, Delete, or running of other macros or VBA Routines) to prepare data ready for Reports.  Here, we are simply adding a message box to display a message instead.  You must create Menus with actions as per the requirements of your Application.

  6. Save the Macro with the name: macProcess and close it.

    The macSubMenu Macro.

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

  8. If the Macro Name Column is not visible then select Macro Name from 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 From Name control using the drop-down control.

  11. Type Process &Data in the Macro Name column in the second row and select the 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 with the name macSubMenu and close it.

    Modify Macro: mcrShortCut

  17. Open the macro mcrShortCut that we have 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 remember on which Form you have attached the earlier macro Shortcut Menu last week, then you can open that Form in normal view and right-click on the Form to display the Form/Report Sub-Menu we added to the earlier menu. If You don't remember then open one of your existing Forms in Design View.

  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 also).

  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 new Group Menu that we have added will appear at the end of the Menu with the 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 Tools Menu.

  6. Click on Create Menu from Macro Option.

    A Menu Bar will appear on top with the label myMenu.

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

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

Quick Toolbar Button.

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

  1. Make a copy of the macros: macMenu, mcrShortCut, and macSubMenu and name them as mac_Menu, mcr_ShortCut, and mac_SubMenu.

  2. Open mcr_ShortCut macro in design view.

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

  4. Open the mac_Menu macro in the 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 mac_Menu Macro.

  7. Click on the mac_Menu Macro to select it.

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

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

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

Share:

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:

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