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

Showing posts with label List Boxes. Show all posts
Showing posts with label List Boxes. Show all posts

Filter Function Output In Listbox-2

Filter Function Output In Listbox-2.

Last week, we explored the Filter() function, a simple example that demonstrates how it works. In that example, we assigned constant values directly to the source array elements to keep the VBA code straightforward and easy to follow.

Just as we can filter data on Forms by setting criteria in the Filter property, or use conditions in Queries to extract information from Tables, the Filter() function provides yet another powerful way to process data — but this time, directly from an Array.

By loading data from a Table or Query into an array, we can use the Filter() function to quickly generate results that match (or exclude) a specified pattern.

To understand this better, let’s try an example using the Employees table from the Northwind.mdb sample database. We’ll create a simple Address Book application that uses the Filter() function to find and display matching names or addresses in a List Box based on user input.

The following section outlines the User Interface (UI) design we plan to create and explains how users will interact with it to display information quickly on the Form.

For this experiment, we will design a Form containing the following controls:

  • A List Box to display the filtered results.

  • A Text Box for entering the search text.

  • A Check Box to toggle between matching and non-matching results.

  • A Command Button to execute the filter operation.

An image of the Form in Design View is shown below:

When the Form opens in Normal View, both the List Box and Text Box controls will be empty.

  • To display all records, the user can type ALL in the Text Box and click the Command Button. This action will load and display the names and addresses of all employees in the List Box.

  • Alternatively, the user can enter a word or phrase — such as part of a name or address — and click the Command Button to display only those records where the entered text appears anywhere within the name or address fields.

If the Matching Cases Check Box is selected, the filter will include only records that match the search text.
If it is not selected, the filter will instead display all records that do not match the entered text.

To provide the user with the functionality described above, we need two Subroutines in the Form’s Code Module and a User-Defined Function in a Standard Module that utilizes the Filter() function.

  1. Form_Load Event:
    When the Form opens, the first Subroutine runs from the Form_Load() event. It reads data — specifically the First Name, Last Name, and Address fields — from the Employees table. These values are combined into a single text string per record and stored in a single-dimensional array variable in memory. This array remains active for as long as the Form is open.

  2. Command Button Click Event:
    The second Subroutine runs when the user clicks the Command Button. It uses the Filter() function to extract matching entries from the source array based on the search text entered in the Text Box control.

    The Filter() function returns all array elements that match (or, optionally, do not match) the specified search text and saves them into a target array variable (xTarget). The resulting data is then formatted and assigned to the Row Source property of the List Box, which displays the filtered results to the user.


The Address Book Project.

Let us prepare for the Address Book's Quick Find Project.

The Design Task.

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

  2. Open a new Form in Design View.

  3. Select the List Box Control from the Toolbox and draw a List Box as shown in the design above.

  4. While the List Box is in the selected state, display the Property Sheet (View -> Properties) and change the following Property Values as given below:

    • Name = AddBook
    • Row Source Type = Value List
    • Width = 4.5"
    • Height = 1.75"
    • Font Name = Courier New
    • Font Size = 10
  5. Position the Child Label attached to the List Box above and change the Caption value to Address Book.

  6. Draw a TextBox below the ListBox. Change the Name Property value of the TextBox to xFind. Position the Child Label above the TextBox and change the Caption value to Search Text/ALL.

  7. Create a Check-Box Control to the right of the Text Box. Change the Name Property of the Check-Box to MatchFlag. Change the Default Value Property to True. Change the Caption value of the child label of Matching Cases.

  8. Create a Command Button to the right of the Check-Box control. Change the Name Property Value of the Command Button to cmdFilter and the Caption Property Value to Filter.

    NB: Ensure that the Name Property Values of the above controls are the same as given above. This is important because we are referencing these names in Programs.

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

  10. Copy and paste the following Code into the Form Module:

    The VBA Code

    Option Compare Database
    Option Explicit
    Dim xSource() As Variant
    
    Private Sub Form_Load()
    Dim db As Database, rst As Recordset, J As Integer
    Dim FName As String * 12, LName As String * 12, Add As String * 20
    
    'Take the count of records
    J = DCount("*", "Employees")
    
    'redimension the array for number of records
    ReDim xSource(J) As Variant
    
    Set db = CurrentDb
    Set rst = db.OpenRecordset("Employees", dbOpenDynaset)
    'load the name and addresses into the array
    J = 0
    Do Until rst.EOF
       FName = rst![FirstName]
       LName = rst![LastName]
       Add = rst![Address]
      xSource(J) = FName & LName & Add
    rst.MoveNext
    J = J + 1
    Loop
    rst.Close
    Set rst = Nothing
    Set db = Nothing
    End Sub
    
    Private Sub cmdFilter_Click()
    Dim x_Find As String, xlist As String, xTarget As Variant
    Dim x_MatchFlag As Boolean, J As Integer
    
    Me.Refresh
    x_Find = Nz(Me![xFind], "")
    x_MatchFlag = Nz(Me![MatchFlag], 0)
    
    'if no search criteria then exit
    If Len(x_Find) = 0 Then
      Exit Sub
    End If
        'initialize list box
        xlist = ""
        Me.AddBook.RowSource = xlist
        Me.AddBook.Requery
    
    If UCase(x_Find) = "ALL" Then
        'Take all values from the Source Array
        'Format it as listbox items
        For J = 0 To UBound(xSource())
          xlist = xlist & xSource(J) & ";"
        Next
    Else    'Call the Filter Function
        xTarget = GetFiltered(xSource(), x_Find, x_MatchFlag)
        'format the returned values as list box items
        If Len(xTarget(0)) > 0 Then
            For J = 0 To UBound(xTarget)
                xlist = xlist & xTarget(J) & ";"
            Next
        End If
    End If
        'remove the semicolon from
        'the end of the list box Value List
        If Len(xlist) > 0 Then
            xlist = Left(xlist, Len(xlist) - 1)
        End If
        'insert the list item string
        'and refresh the list box
        Me.AddBook.RowSource = xlist
        Me.AddBook.Requery
    
    End Sub
  11. Save the Form with the name Filter Form.

  12. Copy and paste the following Function into a Standard Module and save the Module:
    Public Function GetFiltered(ByRef SourceArray() As Variant, ByVal xFilterText As Variant, ByVal FilterType As Boolean) As Variant
        GetFiltered = Filter(SourceArray, xFilterText, FilterType)
    End Function
    

    Filter() Function and Filter Property of the Form.

    We cannot use the Filter() Function in the Form Module because the function name clashes with the Form Property Filter.

    We have placed the Filter() function inside a User-Defined Function named GetFiltered() within a Standard Module, along with the required parameters. This allows us to call it easily from the Form’s Module. The first parameter of the function is passed By Reference, enabling direct access to the source array values without creating a separate copy — improving both performance and efficiency.

    The Demo Runs.

  13. Open the Filter Form in Normal View.

  14. Enter the word ALL (in this case, the Matching Cases flag has no effect) in the Text Box control and click on the Filter Command Button.

    This action will display the names and Addresses of all Employees from the xSource() Array loaded from the Employees Table.

  15. Enter the text Ave in the Text Box and ensure that the 'matching cases' check box is in the selected state.

  16. Click on the Command Button.

    This time, the employees' (Nancy & Laura) Names and Addresses are filtered, and the word Ave in their Address Lines.

  17. Clear the check mark from the 'matching-cases' CheckBox, then click the Filter command button again.

Now, all items except those records having the word Ave will appear in the List Box.

If you review the code we added to the Form Module, you’ll notice that the xSource() array variable is declared in the global section of the module. This allows the same data to be accessed and reused across both Subroutines within the Form Module.

In the Form_Load() Event Procedure, we have declared three Variables as fixed-length String Type (see the declaration line given below).

Dim FName As String * 12, LName As String * 12, Add As String * 20

When we read employee names and Addresses into these Variables, the values will be left-justified inside the Variable, and the balance area of the declared size will be space-filled to the right. This method will space out items at a fixed distance from each other and properly align them when displayed.

It’s important to use a fixed-width font, such as Courier New, for the List Box display. This ensures that all text lines are properly aligned and easy to read. We’ve already configured this setting in Step 4 above.

If you click the Filter Command Button when the TextBox is empty, then the program terminates; otherwise, it calls the GetFiltered() Function and passes the parameter values.

The output Values are returned in the xTarget Array, and the next steps format the Value List and display it in the List Box.

Share:

Filter Function output in ListBox

Filter function output in ListBox.

This FILTER is not related to a Query, SQL WHERE clause, or a Form’s Filter property. It is a built-in VBA function with a useful purpose: quickly filtering data from an array based on text matching.

We can use it to search across multiple fields of data from a Table, extract either matching or non-matching items, and display the results neatly in a List Box.

The Demo Run of the Filter.

But first, will experiment with a simple example to understand its usage. Copy and paste the sample VBA code given below into a Standard Module in your database:

Public Function myFilter()
Dim X(7) As Variant, Y As Variant
Dim J as Integer, msg as String

X(0) = "Strawberry Milk"
X(1) = "Chocolates"
X(2) = "Milkshake"
X(3) = "Mango Juice"
X(4) = "Icecold Milk"
X(5) = "Apple Juice"
X(6) = "Buttermilk"
X(7) = "Vanilla Icecream"

'Extract all items containing the text "milk" from Array X()
'and save the output in Array Y()
Y = FILTER(x, "milk", True, vbTextCompare)
msg = ""
For J = 0 To UBound(Y)
   msg = msg & J + 1 & ". " & Y(J) & vbCr
Next

MsgBox msg

End Function

Click anywhere within the Code and press F5 to run the Code. The function output will be displayed in a MsgBox.


How It Works

Let us examine the above code closely. Variable X is dimensioned for eight elements, and the Array is loaded with text values.

The FILTER() Function in the statement Y = FILTER(X, "milk", True, vbTextCompare) extracts the items that match the search text milk from the Source Array of values from Variable X and saves the output as an array of Values into Variable Y.

The FILTER() Function accepts four parameters.

The first parameter X is the Array containing the Text Values.

The second parameter  milk is the search text. It is compared against each item in the source array X. Whenever a match is found anywhere within an array element, that item is extracted and added as an element in the target array  Y .

The third True parameter value extracts the matched items as output and saves them in Variable Y. When this value is set to False, the output will be items that do not contain the search text milk.

The fourth parameter dictates a specific comparison method: Binary, Database, or Text Comparison. Here, we have used the Text Comparison method. The third and fourth parameters are Optional.

Try the above Code with different search text: juice or Ice, etc.

If you look at the Variable declarations of the Code, you can see that we have declared the Variable Y as a simple Variant Type and not as an Array Variable.

The FILTER() function automatically resizes the target array based on the filter operation result. Because the number of matches can vary with each search, the output array can be of different sizes each time. To handle this dynamically, we use the UBound() function to determine the number of elements in the filtered array. This allows a For...Next loop to iterate through all matching items and format them for display in a form MsgBox or other output.

Important points:

  • The source array must be single-dimensional.

  • The search text can be multiple pieces of information: first name, last name, and address.  You should concatenate all relevant fields into a single string for each record and store them in a single-dimensional array.

The Filter() Function will not work in Code Modules of Forms or Reports.

Real Application Around Filter() Function

I have developed an Application around this Function for our Department Secretary to find Office Files with their location addresses (we have hundreds of them) that match a specific word or phrase in their Subject or Description Fields and display them in a List Box on a Form.

We will try a similar example using employee data, with more than one field value, joined together as source Array contents, and display the Filter result in a List Box. I will give details of this example in the next Article.

In the meantime, you can experiment with using this function for your own tasks. Once I present my example, you can compare it with your approach and examine the differences or improvements.

If you could do it differently, share the idea with me so that I can learn something from you, too.

Share:

Dynamic ListBox ComboBox Contents

Dynamic ListBox ComboBox Contents.

Sometimes, you may want to display different sets of unrelated data in the same List Box — each with its own column layout — and switch between them at will. This switch could happen when the user clicks a button or triggers another event.

Normally, when creating a List Box or Combo Box in MS Access, you choose one of three standard Row Source Type options: Table/Query, Value List, or Field List. You then set other properties such as Column Count, Column Widths, and Bound Column.

However, there’s another, often overlooked option — you can assign a User-Defined Function to the Row Source Type property. This function can dynamically populate the List Box or Combo Box, allowing full control over the data and its layout.

Interestingly, while it’s called a user-defined function, this feature is actually built into Microsoft Access. The documentation provides the structure, required parameters, and basic code template. All you need to do is copy the function, adapt it, and tailor it to suit your specific requirements.

You can view the details of this function directly from the Access Help system. To do this, place the insertion point in the Row Source Type property of a List Box or Combo Box control and press F1.

When the Help window opens, look for the hyperlink titled User-defined Function and click it. This will display detailed information about the function’s parameters and how each one works.

We’ll now examine the second example provided in that Help document. The VBA code below demonstrates how the function is used in a List Box, giving us a clearer understanding of its structure and behavior.

Function ListMDBs(fld As Control, ID As Variant,  row As Variant, col As Variant,  code As Variant) As Variant
Static dbs(127) As String, Entries As Integer    
Dim ReturnVal As Variant

ReturnVal = Null
    Select Case code
        Case acLBInitialize
               ' Initialize.
            Entries = 0
            dbs(Entries) = Dir("*.MDB")
            Do Until dbs(Entries) = "" Or Entries >= 127
                Entries = Entries + 1
                dbs(Entries) = Dir
            Loop
            ReturnVal = Entries
        Case acLBOpen ' Open.
            ' Generate unique ID for control.
            ReturnVal = Timer
        Case acLBGetRowCount
            ' Get number of rows.
            ReturnVal = Entries
        Case acLBGetColumnCount
    ' Get number of columns.
            ReturnVal = 1
        Case acLBGetColumnWidth
   ' Column width.
   ' -1 forces use of default width.
            ReturnVal = -1
        Case acLBGetValue   ' Get data.
            ReturnVal = dbs(row)
        Case acLBEnd  ' End.
            Erase dbs
    End Select
    ListMDBs = ReturnVal
End Function
  1. Copy the above code into a new Standard Module in your Database and save it.

  2. Open a new Form in Design View and create a List Box on it.

  3. Click on the List Box to select it.

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

  5. Insert the Function name ListMDBs in the Row Source Type Property, overwriting the value Table/Query.

  6. Save the Form.

  7. Open the Form in the normal view.

A list of databases from the specified directory (check Tools -> Options -> General Tab for your default directory location) will appear in the List Box. A sample image of a ListBox is given below:


Taking Files-List From a Specific Folder.

You can modify the following line in the program to list Word or Excel files either from the default folder or from a specific folder of your choice.

dbs(Entries) = Dir("*.xls")

OR

dbs(Entries) = Dir("C:\My Documents\*.xls"). The dbs(Entries) = Dir in the subsequent calls uses the first call parameter value "C:\My Documents\*.xls" by default and populates the String Array dbs() in the Initialize step of the Program.

This section of the code can be customized and adapted for various purposes. After the initialization phase, the function is repeatedly called by the system to retrieve other values—such as the row count, column count, and more—that define the List Box’s property values, which are usually set manually during design time.

When the ColumnWidths property is set to -1, it signals Access to retain the default settings specified manually in the Property Sheet. This feature is useful when displaying multiple columns of data with mixed column widths.

Finally, the following statements pass the List Box Source Values dbs(row) that we have created under the Initialize stage for displaying in the List Box:

Case acLBGetValue ' Get data.
ReturnVal = dbs(row)

The Row parameter holds the actual number of items loaded into the dbs() array, which was initially declared with 127 elements. This value is passed to the function through the Entries variable, as shown in the following segment of the code.

Case acLBGetRowCount ' Get the number of rows.
ReturnVal = Entries

The dbs variable is declared as a static, single-dimensioned array with 128 elements (indexed from 0 to 127) so that it retains its values during subsequent calls to the ListMDBs user-defined function. This persistence is important because MS Access repeatedly calls the function at different stages of the List Box population process. During each of these calls, the required parameter values are automatically passed by MS Access — you don’t need to provide them manually.

The first parameter represents the name of the List Box control. The second parameter, ID, helps the system distinguish this specific process from other similar ones that may be running. It is assigned a value based on the System Timer using the following statements:

Case acLBOpen ' Open.
' Generate a unique ID for control.
ReturnVal = Timer

The System Timer generates new values at millisecond intervals, ensuring that each user-defined function instance receives a unique identification value when multiple such functions are active simultaneously.

The Code parameter carries specific values that are evaluated by the function's SELECT CASE statements. These values identify the property or action requested by Microsoft Access, and the corresponding return values used to dynamically define or update the List Box property settings.

Using Table Record Field Values in a ListBox.

If you’ve understood, or at least have a general idea of, how this function defines the contents of a List Box or Combo Box, then we’re ready to move on to the interesting part — the trick I mentioned at the beginning of this article.

Second Example with Employees Table

We will create a copy of the code and modify it to make a List Box that displays two columns — Employee Code and First Name — from the Employees table in the Northwind database.

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

  2. Copy the following VBA Code into the Standard Module of your database and save the Module:

    Function ListBoxValues(fld As Control, ID As Variant, row As Variant, col As Variant, code As Variant) As Variant
        Static xList(127, 0 To 1) As String, Entries As Integer
        Dim ReturnVal As Variant, k As Integer
        Dim db As Database, rst As Recordset, recCount As Integer
    
        ReturnVal = Null
        Select Case code
            Case acLBInitialize  ' Initialize.
                Set db = CurrentDb
                Set rst = db.OpenRecordset("Employees", dbOpenDynaset)
                Entries = 0
                Do Until rst.EOF
                   For k = 0 To 1
                        xList(Entries, k) = rst.Fields(k).Value
                   Next
                   rst.MoveNext
                   Entries = Entries + 1
                Loop
                rst.Close
                ReturnVal = Entries
            Case acLBOpen                    ' Open.
                ' Generate unique ID for control.
                ReturnVal = Timer
            Case acLBGetRowCount
             ' Get number of rows.
                ReturnVal = Entries
            Case acLBGetColumnCount
       ' Get number of columns.
                ReturnVal = 2
            Case acLBGetColumnWidth    ' Column width.
               ' -1 forces use of default width.
                ReturnVal = -1
            Case acLBGetValue                ' Get data.
                ReturnVal = xList(row, col)
            Case acLBEnd                        ' End.
                Erase xList
        End Select
        ListBoxValues = ReturnVal
    End Function
  3. Open the Form in Design View with the ListBox we created earlier.

  4. Click on the List Box to select it.

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

  6. Change the Column Widths Property Value to 0.5";1.5"

    The following lines of Code say to use the values set in the Column Widths property without change:

    Case acLBGetColumnWidth  ' Column width -1 forces the use of the default width.

    ReturnVal = -1

    If the Column Widths property contains only a single value (for example, 1"), then all columns in a multi-column list will automatically use that same width. This may not look visually appealing when the column values vary in length. You can experiment with different width settings to better understand how they affect the List appearance.

  7. Create a Command Button on the Form.

  8. Ensure that the Command Button is in the selected state and display the Property Sheet.

  9. Click on the On Click Property and select [EventProcedure] from the Drop Down control, and click on the Build (...) Button to open the VBA Module with the skeleton of the On Click Event Procedure.

  10. Copy and paste the following lines of code in the middle of the Event Procedure.

    Me.List40.RowSourceType = "ListMDBs"
    Me.List40.Requery
    
  11. Change the name of the List Box (the name in Bold Letters) to match the name of your own List Box.

  12. Create another Command Button below the first one.

  13. Repeat the Procedure in Steps 10 and 11 for the On Click Property of the second Command Button.

  14. Copy and paste the following code in the middle of the On Click Event Procedure:

    Me.List40.RowSourceType = "ListBoxValues"
    Me.List40.Requery
    
  15. Change the name of the List Box (the name in Bold Letters) in the Code to match the name of your own List Box.

  16. Save and Close the Form.

  17. Open the Form in Normal View.

    Since you have already inserted the ListMDBs User Defined Function in the Row Source Type Property earlier, the list of databases will appear in the List Box first.

  18. Click on the second Command Button to change the List Box contents to the Employees List.

    A sample image of the List Box with Employee List is given below:

  19. The Command Button click changes the List Box contents back to the Database List again.

It works for Combo Boxes in the same way. You may create a Combo Box control and run the same functions from the Row Source Type Property.

Don't forget to set the Default Value Property value 1; otherwise, the Combo Box may not show anything in its Text Box area before you select an item from the list.

Share:

List Box and Date Part Two

Continued from LIST BOX AND DATE PART ONE

When working with date values in List Boxes, we’ve seen that it’s often necessary to convert the selected values into a compatible format before using them in data processing tasks. In this section, we’ll explore two additional examples that use different date expressions. Although the resulting output remains the same, the methods of specifying the date parameters will vary.

Typically, we can filter data using a date range — by entering a start date and an end date in text boxes on a report parameter form, or by entering these values directly into parameter queries to extract records from a source table or query. However, in the examples that follow, we’ll approach this task differently to gain a deeper understanding of how to work with date-related expressions in Microsoft Access VBA.

Modifying the Form.

  1. Open the Form LISTBOXDATE that we have created in the earlier example in Design View.

  2. Make a copy of the List Box and paste it into the same area of the Form. Drag and place it on the right side of the Combo Box. See the sample image given below:

  3. Place the child Label on the top and display its Property Sheet (View --> Properties). Change its Caption Property to List (Type-2).

  4. Click on the List Box and display the Property Sheet (if you have closed it), and change the following Properties:

    • Name = List2
    • Row Source Type = Value List
    • Row Source = 01;"Jan";02;"Feb";03;"Mar";04;"Apr";05;"May";06;"Jun";07;"Jul";08;"Aug";09;"Sep";10;"Oct";11;"Nov";12;"Dec"
    • Column Count = 2
    • Column Heads = No
    • Column Width = 0";1.5"
    • Bound Column = 1
    • Default Value = 1
    • Multi Select = None

    At this point, let’s focus on a few important property settings of the List Box.
    First, check the Row Source property. In this example, the List Box items are entered as value pairs, such as 01; "Jan" for January, and so on for the other months. The Column Count property is set to 2, meaning the List Box contains two columns — the numeric value (e.g., 01) in the first column and the corresponding month abbreviation (e.g., Jan) in the second.

    However, when the List Box is displayed, only the second column (Jan, Feb, etc.) appears. This is because of the Column Widths property, which is set to 0";1.5". The first column has a width of  0 inches, effectively hiding it from view.

    Even though it’s hidden, the Bound Column property is set to 1, which means that when a user selects a month, the value from the first (hidden) column — such as 01 — is actually the one returned by the List Box.

    Finally, the Default Value property is set to 1, ensuring that if the user doesn’t make a selection, “Jan” (the first item in the list) is chosen automatically.

  5. Create two TextBoxes to the left of the List Box and below the other TextBoxes. Change the Caption of the child Labels to Method-2 and Method-3.

  6. Change the Property Values of the first Text Box that you have drawn now to the following Values:

    • Name = Method2
    • Control Source = =Format(DateSerial([cboyear],[List2],1),"mmm-yyyy")
  7. Change the Property Values of the second Text Box to the following Values:

    • Name = Method3
    • Control Source = =[cboYear]*100+[List2]
  8. Create a Command Button to the right of the existing two buttons and change the Property Values as shown below:

    • Name = cmdDisplay2
    • Caption = Display-2
  9. Create another Command Button and place it to the right, and change the Property Values as given below:

    • Name = cmdDisplay3
    • Caption = Display-3
  10. Display the VBA Code Module of the Form (View -> Code), and add the following VBA Code into the Module by copying and pasting it below the existing Code:

    Private Sub cmdDisplay2_Click()
    Me.Refresh
    DoCmd.OpenQuery "Display2_listbox", acViewNormal
    End Sub
    
    Private Sub cmdDispaly3_Click()
    Me.Refresh
    DoCmd.OpenQuery "Display3_listbox", acViewNormal
    End Sub
    
  11. Open a New Query in Design View without selecting any file from the displayed list. Open the SQL editing Window (View -> SQL View), copy and paste the following SQL String, and save the Query with the name DISPLAY2_LISTBOX:

    SELECT Orders.*
    FROM Orders
    WHERE (((Format([orderdate],"mmm-yyyy"))=[Forms]![LISTBOXDATE]![Method2]));
    
  12. Open another New Query in Design View, copy and paste the following SQL String into the SQL editing window, and save it with the name DISPLAY3_LISTBOX:
    SELECT Orders.*
    FROM Orders
    WHERE (((Format([orderdate],"yyyymm"))=[Forms]![LISTBOXDATE]![Method3]));
    

    Test Runs

  13. Open the LISTBOXDATE Form in Normal View and click on the Command Button Display-2. The Query DISPLAY2_LISTBOX will open up with filtered output data using the current value in the Text Box with the name Method2. Select different Values in the Year Combo Box and the new List Box and try it again. Check the accuracy of the filtered data.

    NB: If the Query displays an error, then try to link the essential Library Files to your Project. Visit the Page Command Button Animation for details of Library Files and follow the procedures explained there. The Orders Table doesn't have all twelve months of data except for the Year 1997. Check for the Range of months available in the 1996 and 1998 years' data in this Table and select a month for available data for testing.

    Every time you select different Values in the List Box and the Combo Box, the value in the TextBox with the names Method2 and Method3 also changes. Close the Datasheet View of the Query before clicking the Command Button with a different selection of values.

  14. Click on the Command Button Display-3 to open the Query DISPLAY3_LISTBOX with the filtered output using the Text Box named Method3 Value.

NB: You must change the Visible Property of these TextBoxes to No to keep them hidden from your Application Users. Study the expressions written in the TextBoxes and their corresponding Formula written in the Query Column to compare both values.

The List Box Settings

We used the Multi-Select Property of the List Boxes in the first two articles, Selected List Box Items and Dynamic Query, and Create List from Another List Box With Simple and Extended value settings,  but here we turned it off.

When you open the Form containing the List Boxes (with their Multi-Select property set to either Simple or Extended) for the first time, the Text Boxes that depend on expressions using values from these List Boxes will automatically display results based on the Default Value property, if one is defined. However, once you start interacting with the List Box—by clicking on an item—the Text Boxes may display #Error or become blank.

When the Multi-Select property is set to Simple, you can select or deselect items by clicking them one at a time.
When it is set to Extended, you can:

  • Select a range of adjacent items by clicking the first and last items while holding down the SHIFT key, or by clicking and dragging the mouse across the list (without using SHIFT).

  • Select non-adjacent items by holding the CTRL key and clicking on each desired item individually — just as you would in Simple mode.

We used the Multi-Select Property value equal to None (default setting) because our examples presented here work on a single item from the List Box.

Share:

List Box and Date Part One

Date Selection ListBox.

One of our dedicated readers, Mr. Nick Els from South Africa, has proposed an insightful idea for an Article focusing on the practical applications of ListBoxes with date-related settings. This marks the beginning of a two-part series dedicated to exploring this specific topic. Please review our previous posts on Selected List Box Items and Dynamic Query, and create a List from Another List Box for a comprehensive understanding leading up to this series.

Descriptive names of the Months or their numerical form combined with Year Values from Combo Boxes or List Boxes can be used in various ways to compare with Date Field values in Queries for filtering data. I have mentioned the term variety because all methods require creating expressions at the Query level or in Text Boxes on Forms to reformat the values into a compatible type before they are compared. We will split this article into two parts instead of overcrowding it with all of them here.

List Boxes can be created in Data Entry Forms, Main Switchboards (Control Screen) for opening Forms or Reports, or on Report Parameter Forms for use in Queries for Data Processing tasks, and so on. One or more Values from List Boxes can be selected and used directly with queries or VBA Routines to filter data from underlying tables, as we did in the earlier examples with List Boxes.

A reference to the selected List Box item can be set directly in a Query Criteria Row or extracted the selected value into a Text box with the help of a formula (like =[List1] in the Control Source property) and referenced it in the Query to Filter Values from the underlying Table.

There are a few important aspects to understand about the Multi-Select property settings of List Boxes,  their advantages, limitations, and how they affect expressions that reference selected items in Text Boxes or Query Criteria. These topics will be explored in greater detail in the second part of this article, rather than delving too deeply into them here, and risking unnecessary complexity at this stage.

Get Northwind Sample Tables.

  1. Download the following four tables from the Northwind.mdb sample database. For now, we will be using only the Orders table. However, since the Orders table contains references to other tables, missing those related tables in your project may cause errors when opening queries based on the Orders table.

    If you’re unsure where the Northwind.mdb sample database is located, refer to the page Saving Data on Forms Not in a Table for location details and reference instructions.

    If you prefer to use a Table from your own project, you may do so, but you have to edit the expressions to change the Table Name and Field Names presented here before they are used with your Table.

    • Orders
    • Customers
    • Employees
    • Shippers
  2. Copy and paste the following SQL String into the SQL Editing window of a new Query and save the Query with the name OrderYearQ.

    SELECT Year([OrderDate]) AS OrderYr
    FROM Orders
    GROUP BY Year([OrderDate]);
    
  3. Open a New Form in Design View. If the Toolbox is not visible, then select Toolbox from the View Menu.

    Designing a Form with a List Box.

  4. De-select the Control Wizard (top-right control on the Toolbox) if it is in the selected state. Select the ListBox Tool and draw a ListBox as shown in the design below.

  5. Click on the Child Label attached to the List Box and display the Property Sheet (View -> Properties), change the Caption Property to List1 (Type-1), and position the Label above the List Box.

  6. Select the List Box, display the Property Sheet (if you have already closed it), and change the following property values as indicated against each one:

    • Name = List1
    • Row Source Type = Value List
    • Row Source = "January";"February";"March";"April";"May";"June";"July";"August";"September";"October";"November";"December"
    • Column Count = 1
    • Column Widths = 1.5"
    • Bound Column = 1
    • Default Value = "January"
    • Multi Select = None
  7. Turn on the Control Wizard that we have disabled in Step 5. Select the Combo Box Tool and draw a Combo Box at the top and to the right of the List Box. Select the OrderYearQ Query that we have created in Step 1 from the Queries List.

  8. Change the following Property Values of the Child Label and the Combo Box:
    • Child Label: Caption = Year
    • Combo Box: Name = cboYear
    • Column Count = 1
    • Column Heads = No
    • Column Widths = 0.5"
    • Bound Column = 1
    • List widths = 0.5"
    • Default Value = =DMin("orderyr","orderyearQ")+1
  9. Create a Text Box below the Combo Box and change its Child Label Caption to Method-1. Select the Text Box and change the following Properties:
    • Name = Method1
    • Control Source = =Format(DateValue("01" & "-" & [List1] & "-" & [cboyear]),"yyyymm")

    The Visible Property of this Control can be set to No to hide it from Users if needed.

  10. Create two Command Buttons below the List Box.
  11. Change the first Command Button's Name Property to cmdDisplay0 and change the Caption Property to Display-0.
  12. Create a second Command Button to the right of the earlier one and change the Name Property to cmdDisplay1 and the Caption Property to Display-1.

    The Form Class Module Code.

  13. Display the VBA Module of the Form (View -> Code), copy and paste the following VBA Code into the Module, and save the Form with the name LISTBOXDATE.
    Private Sub cmdDisplay0_Click()
    Me.Refresh
    DoCmd.OpenQuery "Display0_listbox", acViewNormal
    End Sub
    
    Private Sub cmdDisplay1_Click()
    Me.Refresh
    DoCmd.OpenQuery "Display1_listbox", acViewNormal
    End Sub
    

    Note: You must save the Form with the above name for our examples. We will be setting references to the List Box, Combo Box, and Text Box on this Form to use their current values in Query Criteria Rows.

    Sample Queries.

  14. Open a new Query in Design View without selecting any of the Files displayed. Display the SQL Window (View -> SQL View), copy and paste the SQL string given below, and save it with the name DISPLAY0_LISTBOX.
    SELECT Orders.*,
     Format([orderdate],"mmmm") AS MTH,
     Year([ORDERDATE]) AS XYEAR
    FROM Orders
    WHERE (((Format([orderdate],"mmmm"))=[Forms]![LISTBOXDATE]![List1]) AND ((Year([ORDERDATE]))=[Forms]![LISTBOXDATE]![cboYear]));
    
  15. Create another Query with the following SQL string and save it with the name DISPLAY1_LISTBOX.
    SELECT Orders.*
    FROM Orders
    WHERE (((Format([OrderDate],"yyyymm"))=[Forms]![LISTBOXDATE]![Method1]));
    

    Test Runs.

  16. Open the Form LISTBOXDATE in Normal View.

  17. By default, January is selected in the List Box, and the Year 1997 is set in the Year Combo Box as the default value.

    The Text Box below the Combo Box displays the result of the formula that we have written using the List Box's current selection of the month and the Combo Box value combined.

    The two Queries that we have created use different methods to reference the contents of the List Box and the Combo Box.

  18. Select a month from the List Box. Select a different Year in the Combo Box, if needed (but be careful with the month selection because not all twelve months' data are available except for the year 1997 in the Orders Table).
  19. Click on the Command Button with the Caption Display-0. The DISPLAY0_LISTBOX Query will open in Datasheet view with the data corresponding to the Month and Years settings in the List box and the Combo box, respectively. Close the Datasheet View of the Query before trying it out with the different settings.

    NB: If the Query displays an error, then link the essential Library Files to your Project. Visit the Page Command Button Animation for details of Library Files and follow the procedures explained there.

  20. Open the first Query DISPLAY0_LISTBOX in the design view and check the criteria settings that we have created to compare the Order Date with the settings on the Form.

    We have created two columns with expressions for converting the Order Date Value into the descriptive name of the Month in the first column, and extracting the Year Value in the second Column. On the criteria row, we have set a direct reference to the selected month in the ListBox, and the second column criteria are set with a reference to the current value of the ComboBox.

  21. Click the Command Button with the Caption Display-1.

It will open the second Query DISPLAY1_LISTBOX with the same result. But this query has only one column with an expression to compare the value with the Text Box contents on the Form. The Text box has the formula =Format(DateValue("01" & "-" & [List1] & "-" & [cboyear]), "yyyymm") to combine both Month and Year values, from the List Box and the Combo box respectively, together and referenced from the Query criteria row.

Study the expressions written in the Queries and in the Form controls and try to understand how they work. You may create TextBoxes and Queries using the same ListBox and ComboBox values and try them out, which will give you more insight into these methods.

Share:

Create List from another Listbox.

Create List From Another ListBox.

If you haven’t tried the earlier example, Selected List Box Items and Dynamic Query, please visit that page and complete it before proceeding. The same table and queries created in that example will also be used here.

Here’s a brief overview of what you need to do before continuing:

  1. Import the Orders table from the Northwind.mdb sample database.

  2. Create two Select Queries by copying and pasting the SQL strings provided below into the SQL editor window.

  3. Save the queries using the suggested names.

  1. Query: OrdersinQ
    SELECT Orders.*
    FROM Orders
    WHERE ((([Orders].[OrderDate]) Between #5/1/1998# And #5/31/1998#));
    
  2. Query: OrdersOUTQ
    SELECT OrdersINQ.*
    FROM OrdersINQ
    WHERE (((OrdersINQ.OrderID) In (11067)));
    

In the earlier example, we used a method where selected items were highlighted and used directly as criteria for the output query. In this example, we’ll achieve the same result using a different approach — in several creative ways.

When you create a Form using the Microsoft Access Form Wizard, it displays a list of available fields from the source table or query in one list box and allows you to select which fields to include on the form. You can move the selected fields to another list box and add or remove fields before proceeding to the next step.

We’re going to create something similar to that.

To try this method, we’ll use two list boxes on a form:

  • When the form opens, the first list box will be populated with Order Numbers and Customer Codes from the source query OrdersinQ, which we used in the earlier example, Selected List Box Items and Dynamic Query.

  • The user can then select one or more items from the first list box and click a command button with a right-arrow (>) indicator to move the selected items to the second list box — while simultaneously removing them from the first.

A sample image showing the form in action is provided below.

The List Boxes Image

If the user changes her mind and wants to remove one or more items from the second list, she can do so by highlighting the desired items and clicking the second command button (with the left arrow < as its indicator). The selected items will then be moved back into the original list and removed from the second list box. The user can repeat this process any number of times until satisfied with the final selection, and then click the Preview Orders button to open the output query OrdersOutQ, or a report or form based on it.

The selected order numbers are extracted from the list and used to redefine the SELECT query OrdersOutQ, as we did in the previous example.

Since this approach is different from what we have implemented earlier, it requires an additional ListBox and three more event procedures to handle the item transfers and interactions.

The Form_Load() event procedure is used to populate the first ListBox dynamically, instead of assigning the OrdersInQ query as its Row Source manually. This design gives the user full control to move items freely between the two lists while automatically removing moved entries from the source list.

Because of this dynamic behavior, we cannot directly use the OrdersInQ query as the Row Source for the list box, as we did in the earlier example. Instead, we must populate it through VBA code to maintain full control over the item transfers.

Preventing Multiple Item Selection

We can easily implement another variation of this technique with just a single line change in each of the click event procedures of the command buttons—and even remove both command buttons entirely.

Simply change the header line
Private Sub cmdIn_Click() to Private Sub List1_Click()

for the first command button, and likewise change

Private Sub cmdOut_Click() to Private Sub List2_Click()

for the second command button. With these minor edits, both command buttons become unnecessary and can be safely deleted from the form.

However, note that multiple item selection will not be possible with this approach, since each item is transferred immediately when clicked.

You now have three distinct methods for working with list boxes—each suited to different scenarios in your projects. Use them as needed, and demonstrate your versatility in handling list box interactions with creative approaches.

  1. Open a New Form in Design View.

  2. Disable the Control Wizard on the Toolbox and create a List Box on the Form. Change the Label Caption to Orders.

  3. Click on the List Box and display the Property Sheet (View -> Properties) and change the following Properties:

    • Name = List1

    • Row Source Type = Value List

    • Column Count = 2

    • Bound Column = 1

    • Column Width = .5";1"

    • Multi Select = Simple

  4. Select the existing List Box, then copy and paste it to the right side of the form, leaving enough space between the two List Boxes to accommodate the Command Buttons (as shown in the design above). Change the Name property of the newly created List Box to List2, and verify that all other property settings match those of the original List Box. Finally, update the Caption of the attached label to “Selected Orders.”

  5. Create two small Command Buttons in between the List Boxes. Change the Name Property of the top one to cmdin, and put a greater than symbol (>) in the Caption Property.

  6. Change the Name Property of the second Command Button to cmdout and insert a less-than symbol (<) in the Caption Property.

  7. Create another Command Button below both List Boxes. Change the Name Property to cmdPreview and change the Caption Property to Preview Orders.

  8. Select File -> Save and save the Form named ORDERLIST.

  9. Display the VBA Code Module of the Form (View -> Code). Copy and paste the following code into the VBA Module of the Form.

    Form Class Module Code.

    Private Sub Form_Load()
    '------------------------------------------------------
    'Author: a.p.r. pillai
    'Date  : 10/05/2008
    'URL   : http://www.msaccesstips.com
    'All Rights Reserved by msaccesstips.com
    '------------------------------------------------------
    Dim db As Database, rst As Recordset
    Dim xinlist As ListBox, strlist As String
    
    Set db = CurrentDb
    Set rst = db.OpenRecordset("OrdersinQ", dbOpenDynaset)
    Set xinlist = Me.List1
    strlist = ""
    
    Do While Not rst.EOF
        If Len(strlist) = 0 Then
            strlist = rst![OrderID]
            strlist = strlist & ";" & Chr$(34) & rst![CustomerID] & Chr$(34)
        Else
            strlist = strlist & ";" & rst![OrderID]
            strlist = strlist & ";" & Chr$(34) & rst![CustomerID] & Chr$(34)
        End If
    rst.MoveNext
    Loop
    rst.Close
    
    xinlist.RowSource = strlist
    xinlist.Requery
    End Sub
    

     

    Private Sub cmdin_Click()
    '------------------------------------------------------
    'Author: a.p.r. pillai
    'Date  : 10/05/2008
    'URL   : http://www.msaccesstips.com
    'All Rights Reserved by msaccesstips.com
    '------------------------------------------------------
    Dim xinlist As ListBox, xoutlist As ListBox, strRSource As String
    Dim listcount As Long, j As Long, strRS2 As String
    
    Set xinlist = Me.List1
    Set xoutlist = Me.List2
    
    listcount = xinlist.listcount - 1
    strRSource = xoutlist.RowSource
    strRS2 = ""
    
    For j = 0 To listcount
        If xinlist.Selected(j) = True Then
            If Len(strRSource) = 0 Then
                strRSource = xinlist.Column(0, j)
                strRSource = strRSource & "; " & Chr$(34) & xinlist.Column(1, j) & Chr$(34)
            Else
                strRSource = strRSource & ";" & xinlist.Column(0, j)
                strRSource = strRSource & ";" & Chr$(34) & xinlist.Column(1, j) & Chr$(34)
            End If
        Else
            If Len(strRS2) = 0 Then
                strRS2 = xinlist.Column(0, j)
                strRS2 = strRS2 & ";" & Chr$(34) & xinlist.Column(1, j) & Chr$(34)
            Else
                strRS2 = strRS2 & ";" & xinlist.Column(0, j)
                strRS2 = strRS2 & "; " & Chr$(34) & xinlist.Column(1, j) & Chr$(34)
            End If
        End If
    Next
    xoutlist.RowSource = strRSource
    xinlist.RowSource = strRS2
    xoutlist.Requery
    xinlist.Requery
    End Sub
    

     

    Private Sub cmdout_Click()
    '------------------------------------------------------
    'Author: a.p.r. pillai
    'Date  : 10/05/2008
    'URL   : http://www.msaccesstips.com
    'All Rights Reserved by msaccesstips.com
    '------------------------------------------------------
    Dim xinlist As ListBox, xoutlist As ListBox, strRSource As String
    Dim listcount As Long, j As Long, strRS2 As String
    
    Set xinlist = Me.List1
    Set xoutlist = Me.List2
    
    listcount = xoutlist.listcount - 1
    
    strRSource = xinlist.RowSource: strRS2 = ""
    For j = 0 To listcount
        If xoutlist.Selected(j) = True Then
            If Len(strRSource) = 0 Then
               strRSource = xoutlist.Column(0, j)
                strRSource = strRSource & ";" & Chr$(34) & xoutlist.Column(1, j) & Chr$(34)
            Else
                strRSource = strRSource & "; " & xoutlist.Column(0, j)
                strRSource = strRSource & ";" & Chr$(34) & xoutlist.Column(1, j) & Chr$(34)
            End If
        Else
            If Len(strRS2) = 0 Then
                strRS2 = xoutlist.Column(0, j)
                strRS2 = strRS2 & ";" & Chr$(34) & xoutlist.Column(1, j) & Chr$(34)
            Else
                strRS2 = strRS2 & ";" & xoutlist.Column(0, j)
                strRS2 = strRS2 & ";" & Chr$(34) & xoutlist.Column(1, j) & Chr$(34)
            End If
        End If
    Next
    xinlist.RowSource = strRSource
    xoutlist.RowSource = strRS2
    xoutlist.Requery
    xinlist.Requery
    End Sub
    

     

    Private Sub cmdPreview_Click()
    '------------------------------------------------------
    'Author: a.p.r. pillai
    'Date  : 10/05/2008
    'URL   : http://www.msaccesstips.com
    'All Rights Reserved by msaccesstips.com
    '------------------------------------------------------
    Dim strsql0 As String, crit As String, strsql As String
    Dim db As Database, qryDef As QueryDef, crit0 As String
    Dim strOrders As String, xoutlist As ListBox, listcount As Integer
    Dim j As Integer
    
    strsql0 = "SELECT Orders.* FROM Orders "crit0 = "WHERE (((Orders.OrderID) In ("
    
    Set xoutlist = Me.List2
    listcount = xoutlist.listcount - 1
    If listcount < 0 Then
        strsql = strsql0 & ";"
        GoTo nextstep
    End If
    
    For j = 0 To listcount
        If Len(strOrders) = 0 Then
            strOrders = xoutlist.Column(0, j)
        Else
           strOrders = strOrders & "," & xoutlist.Column(0, j)
        End If
    Next
    strsql = strsql0 & crit0 & strOrders & "))); "
    nextstep:
    Set db = CurrentDb
    Set qryDef = db.QueryDefs("OrdersoutQ")
    qryDef.Sql = strsql
    db.QueryDefs.Refresh
    DoCmd.OpenQuery "OrdersOutQ", acViewNormal
    End Sub
    
  10. Display the Property Sheet of the Command Buttons and check whether the setting [Event Procedure] is appearing in the On Click property. If not, then select [Event Procedure] from the drop-down list on the right side and save the Form.

  11. Open the Form in normal view and select any number of items one by one in the first ListBox, and click the Command Button with the > indicator. The selected items will move from the first list into the second ListBox.

  12. Select one or two items from the right-side ListBox and click the Command Button with the < indicator. The selected items will move back to the end of the first list. Try the selection method this way a few more times.

  13. When you have completed the selection process, click the Preview Orders Command Button.

Using the Output Query.

The OrderOUTQ Query will open in Datasheet View with the filtered data with the selected Order Numbers. You can use this Query for preparing Reports or designing Forms to display the contents, or use it as the source for other processing steps.

If the right-side List Box is empty when you click the Preview Order command button, the OrderOUTQ Query will pick all the Items from the OrdersINQ for Output.

Share:

Selected List Box Items and Dynamic Query

Dynamic Query.

The Billing Department of Northwind Traders processes customer orders selectively for shipment. An Order Selection Screen is given with a List Box that allows users to highlight specific Order Numbers, filter those selected orders from the main database, and prepare the corresponding Customer Invoices and Shipping Documents. The system also provides the flexibility to process all orders listed in the box when required.

The items displayed in the List Box are records retrieved from the main Orders file based on a specified date range. By adding two text boxes to capture the start date and end date, users can easily control which records appear in the list. However, for the sake of simplicity in this example, we will focus on working directly with the items selected from the List Box.

Get Orders Table from Northwind.mdb

We need the Orders Table from the Northwind.mdb sample Database for our example.

  1. Import the Orders Table from the sample Database NorthWind.mdb, if it has not already been done in our earlier examples. If you don't know the exact location of this Database on your PC, visit the page: Saving Data on Form not in Table, for its location references.

    The SQL for the sample Query.

  2. Copy and paste the following SQL String into a new Query's SQL editing window and save the Query with the Name OrdersINQ
    SELECT Orders.* 
    FROM Orders
    WHERE (((Orders.OrderDate) Between #5/1/1998# And #5/31/1998#));

    With the above query, we are selecting all Orders for May 1998 for the List Box items. The criterion is set as a constant in the Query.

  3. Copy and paste the following SQL String into another Query's SQL editing window and save it with the Name OrdersOUTQ
    SELECT Orders.*
    FROM Orders
    WHERE (((Orders.OrderID) In (11071)));

    The second Query definition will be changed (the criteria part) dynamically, based on the selection of items from the List Box.

    Design a Sample Form.

  4. Open a new Form in Design View.

  5. If the Toolbox is not visible, click the Toolbox button on the Toolbar above or select Toolbox from the View Menu.

  6. Ensure that the Control Wizard button (top right on the Toolbox) is selected. Select the List Box Control on the Toolbox and draw a List Box on the Form as shown in the design image below.


  7. On the List Box Wizard, ensure that "I want the List box to look up the values in a Table or Query" is selected and click Next.

  8. Select the Queries Option in the next view to display the Queries List. Scroll down the list and find the Query with the name OrdersINQ, select it, and then click Next.

  9. Select the Fields OrderID and CustomerID from the Available Fields list and move them to the Selected List window, click Next, and then click Finish.

  10. Align the List Box and its child Label as shown in the sample design above.

  11. Click the ListBox and display the Property Sheet (View -> Properties) and change the following Property Values as given below:

    • Name = List1

    • Multi Select = Simple

  12. De-select the Control Wizard Button on the Toolbox and select the Command Button Tool and draw a Command Button underneath the List Box.

  13. Select the Command Button, display the Property Sheet if it is not visible, and change the following property Values:

    • Name = cmdView

    • Caption = View Orders

  14. Create another Command Button to the right of the earlier one. Display the Property Sheet and change the following Property Values:

    • Name = cmdReset

    • Caption = Reset

    The Form's Class Module Code.

  15. Display the Code Module of the Form (View -> Code). Copy and paste the following VBA Code into the Form Module and save the Form.

    Private Sub cmdview_Click()
    '-----------------------------------------------------------------------
    'Author : a.p.r. pillai
    'Date   :  01/05/2008
    'URL    :  www.msaccesstips.com
    'All Rights Reserved by msaccesstips.com
    '-----------------------------------------------------------------------
    Dim strsqlO As String, crit As String, strsql As String
    Dim db As Database, qryDef As QueryDef
    Dim strOrders As String, xoutlist As ListBox, listcount As Integer
    Dim j As Integer, selectcount As Integer
    
    strsql0 = "SELECT OrdersINQ.* FROM OrdersINQ "
    crit = "WHERE (((OrdersINQ.OrderID) In ("
    
    Set xoutlist = Me.List1
    listcount = xoutlist.listcount - 1
    
    strOrders = "": selectcount = 0
    For j = 0 To listcount
      If xoutlist.Selected(j) = True Then
        selectcount = selectcount + 1
        If Len(strOrders) = 0 Then
           strOrders = xoutlist.Column(0, j)
        Else
           strOrders = strOrders & ", " & xoutlist.Column(0, j)
        End If
      End If
    Next
    
    If selectcount = 0 Then
       strsql = Trim(strsql0) & ";"
    Else
       strsql = strsql0 & crit & strOrders & "))); "
    End If
    
       Set db = CurrentDb
       Set qryDef = db.QueryDefs("OrdersOUTQ")
       qryDef.Sql = strsql
       db.QueryDefs.Refresh
       DoCmd.OpenQuery "OrdersOUTQ", acViewNormal
    
       Set db = Nothing
       Set qryDef = Nothing
    End Sub

     

    Private Sub cmdReset_Click()
    '-----------------------------------------------------------------------
    'Author : a.p.r. pillai
    'Date   :  01/05/2008
    'URL    :  www.msaccesstips.com
    'All Rights Reserved by msaccesstips.com
    '-----------------------------------------------------------------------
    Dim xoutlist As ListBox, j As Integer
    Dim listcount As Integer
    
    Set xoutlist = Me.List1
    listcount = xoutlist.listcount - 1
    For j = 0 To listcount
      If xoutlist.Selected(j) = True Then
         xoutlist.Selected(j) = False
      End If
    Next
    End Sub

    Test Run of the Program.

  16. Open the Form in Normal View. Select a few Orders one by one in the ListBox. You can click the desired item again to deselect it or click the Reset Command Button to deselect all.

  17. Click on the View Orders Command Button to redefine the second Query OrdersOUTQ and open it to show the selected Orders in Datasheet View.

If you need all items in the List for output, then click the Orders View Command Button without making any selection, or after clicking the Reset Command Button.

You can use the OrdersOutQ Query with selected items as a Source to link with other Queries or related Tables and design Reports to print Invoices or design a Screen to display selected Order Details.

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