Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Table Records in Collection Object and Form

Introduction.

Data records from a table will be added as items in a Collection object, with the Description field values used as the Key parameter for each item.

The source values for a ComboBox on a form are also taken from the Description field of the table. Selecting an item from the ComboBox will use its value as the key to retrieve the corresponding record from the Collection object and display the field values in unbound text boxes on the form.

For experimentation, we have created a small table, Table 1, with a few sample records.

The Table image is given below:

The Table Structure image is given below for reference.

The Sample Demo Form.

We have designed a small form with a Combo box on the header of the Form.  The Row Source Property of the Combo box is set with the following SQL:

SELECT [Table1].[Desc] FROM Table1 ORDER BY [Desc]; 

To pick the Desc field value as the Row Source of the Combo Box.

Four text boxes with their Child Labels are added in the Detail Section of the Form.  The Text Box Name Property values are set with the same name as each field on the Table, for easier reference in the Program, in the same order, they appear on the Table.

The design image of the frmtable1 is given below:

The Normal View of the Form frmTable1, with data displayed from the Collection Object, is given below for reference.  The Combo box contents are also shown in the Form.

The following code runs in the frmTable1 Form’s Class Module.  If you have already designed the above Form, ensure that the text boxes are set with the field name of the Table structure shown above.  The Combo box name is cmbDesc.  You can download a database with the Code from the link given at the end of this Page. 

Form Module Code.

Copy and paste the following Code into the frmTable1’s Class Module:

Option Compare Database Option Explicit Private Coll As Collection Dim txtBox() As String Private Sub Form_Load() Dim db As Database Dim rst As Recordset Dim flds As Long, k As Long

Dim frm As Form, Sec As Section, ctl As Control Dim Rec() As Variant, strKey As String 'Open Table1 to upload records into Collection Object Set db = CurrentDb Set rst = db.OpenRecordset("Table1", dbOpenDynaset) 'get record fields count flds = rst.Fields.Count - 1

'Set Detail Section of Form to scan for Text Boxes Set frm = Me Set Sec = frm.Section(acDetail) 'Redim txtBox() to save Textbox names from Form 'to display field values ReDim txtBox(0 To flds) As String 'Get Text Box Names & save into txtBox() Array from Detail Section of Form 'this will be used in ComboBox AfterUpdate Event Procedure k = 0 For Each ctl In Sec.Controls If TypeName(ctl) = "TextBox" Then txtBox(k) = ctl.Name k = k + 1 End If Next

'instantiate Collection Object Set Coll = New Collection

'Redimension Rec Array for number of fields in Table ReDim Rec(0 To flds) As Variant 'Add each record into the Collection Object Do While Not rst.EOF 'Get current record field values into Rec Variant Array For k = 0 To flds Rec(k) = rst.Fields(k).Value Next

'Description Field Value as Key strKey = rst.Fields("Desc").Value 'Add record to the Collection Object with Key Coll.Add Rec, strKey rst.MoveNext Loop rst.Close Set rst = Nothing Set db = Nothing End Sub

Private Sub cmbDesc_AfterUpdate() Dim strD As String, R As Variant Dim j As Long, L As Long, H As Long 'Get Selected Collection Key from ComboBox strD = Me![cmbDesc] 'Retrieve the record from Collection 'using Collection KEY and save the field 'Values into the Variant Variable R = Coll(strD) L = LBound(R) H = UBound(R) 'Add Field Values into corresponding Text Boxes For j = L To H Me(txtBox(j)) = R(j) Next Me.Refresh End Sub Private Sub Form_Unload(Cancel As Integer) 'Remove Collection from Memory on Form Close Set Coll = Nothing End Sub

This is how it works:

  1. All Records from the Table are added as the Collection Object Items in the Form_Load() Event Procedure.  The record description Field (Desc) value is used as the Key parameter value of the Item method.

  2. The Desc field values are also used as Combo Box List values on the Form.

  3. When the user selects an item from the Combo Box, the cmbDesc_AfterUpdate() event procedure retrieves the record from the Collection Object, using the Key value chosen from the combo box, and displays the record field values in the Text Boxes on the Form.

  4. The Objects are cleared from memory when the Form is closed.

In the declaration area of the module, we declare the Collection object Coll and an empty array txtBox().

Within the Form_Load event procedure, the Database object db and Recordset object rst are declared. Next, the variable flds is declared to store the count of record fields.

Form, Section, and Control objects are also declared. These are used to locate text boxes on the form, collect their Name property values, and store them in the txtBox array.

A Variant array Rec() is used to temporarily hold record field values before adding them as a single record item to the Collection object.

The string variable strKey is used to assign the record’s Description field value, which will serve as the key for the current record in the Collection object. Each key in the Collection must be unique.

Note: The VBA code lines are commented appropriately. Go through the code line by line a second time to fully understand its purpose.

The Form_Load() event procedure does the following:

  1. The procedure opens Table1 and reads the field count of the first record, storing it in the variable flds.

  2. The form’s Detail Section is assigned to the sec object variable.

  3. All TextBox controls within the Detail Section of the form are located, and their Name properties are collected into the txtBox() array.

  4. Next, the Collection object is instantiated as the object variable Coll.

  5. At the start of the Do While…Loop, the field values of the current record are added to the Rec Variant array.

  6. The Description (Desc) field value is saved into the string variable strKey.

  7. The statement Coll.Add Rec, strKey adds the current record’s values from Rec as a new item in the Collection, using strKey as the key.

  8. The statement rst.MoveNext advances the record pointer to the next record, and this process repeats until all records in the table have been added to the Collection.

  9. Finally, the Table1 recordset is closed.

At the Form Load Event Procedure, all the records in the Table are loaded into the Collection Object.  The Combo Box in the Form’s Header Section is populated with the values from the table’s Description field.

When a user selects an item from the Combo Box, the cmbDesc_AfterUpdate() event procedure is triggered.

The selected Combo Box value is stored in the variable strD, which is then used in the statement R = Coll(strD) to retrieve the corresponding record array from the Collection using strD as the Key. Alternatively, R = Coll.Item(strD) works equally well.

Notice that the Variant variable R is not explicitly declared as an array. VBA automatically determines the correct data type and dimensions based on the record retrieved from the Collection.

The next steps in the VBA code calculate the lower and upper bounds of the array and use them as control values in a For … Next loop. This loop copies the record field values into the corresponding Text Boxes on the Form, using the Text Box names stored in the txtBox array.


Download the Demo Database.

Download TableColl2003.zip

Download TableColl2007.zip


  1. MS-Access Class Module and VBA
  2. MS-Access VBA Class Object Arrays
  3. MS-Access Base Class and Derived Objects
  4. VBA Base Class and Derived Objects-2
  5. Base Class and Derived Object Variants
  6. Ms-Access Recordset and Class Module
  7. Access Class Module and Wrapper Classes
  8. Ms-Access and Collection Object Basics
  9. Ms-Access Class Module and Collection Object
  10. Table Records in Collection Object and Form
  11. Dictionary Object Basics
  12. Dictionary Object Basics-2
  13. Sorting Dictionary Object Keys and Items
  14. Display Records from Dictionary to Form
  15. Add Class Objects as Dictionary Items
  16. Update Class Object Dictionary Item on Form
Share:

Ms-Access Class Module and Collection Object

Introduction.

Last week, we had a brief introduction to the basics of the Collection object. We learned how to add items to a Collection and retrieve them using various methods. In our earlier examples, we used mixed data types as Collection items, but those were intended purely for demonstration purposes.

In practical use, a Collection typically holds items of a single data type or objects (such as class modules) along with their properties and methods.

We have already become familiar with the following Collection object methods:

  • Add – Adds an item to the Collection.

  • Count – Returns the total number of items in the Collection.

  • Item – Takes an item’s sequence number (index) as a parameter and returns that specific item.

  • Remove – Takes an item’s sequence number (index) as a parameter and deletes that item from the Collection.

The Add method also has four parameters—Item, Key, Before, and After—whose usage we explored earlier.

Now, let us move on to a real-world example of using the Collection object.

The sample VBA code below demonstrates how to use the ClsArea class (which we created earlier to calculate the area of rectangular rooms or objects) with a Collection object. Previously, we used an array of ClsArea class objects to calculate the area of several rooms. This time, we will use a Collection object instead of an array to create and store details of multiple rooms. We can then retrieve these items as needed and display their details in the Debug window.

Adding a Class Object to the Collection.

  1. Open your database and display the VBA Window (ALT+F11).

  2. Copy and paste the following VBA Code into a Standard Module:

    Public Sub Coll_TestOne()
    Dim Arr As ClsArea
    Dim objColl As Collection, obj As Object
    Dim j As Integer, iMax As Integer
    Dim strName As String
    
    iMax = 5
    
    'instantiate the Collection object in memory
    Set objColl = New Collection
    
    'Create a Collection of five ClsArea Object
    'with it's Property values filled-in
    For j = 1 To iMax
        Set Arr = New ClsArea
        
        strName = "Bed Room" & j
        Arr.strDesc = strName
        Arr.dblLength = 20 + j
        Arr.dblWidth = 15 + j
        
      objColl.Add Arr 'Add current Class Object to Collection
      
        Set Arr = Nothing
    Next
    
    'Printing Section
    Debug.Print "Description", "Length", "Width", "Area"
    For Each obj In objColl
        With obj
            Debug.Print .strDesc, .dblLength, .dblWidth, .Area
        End With
    Next
    
    Set objColl = Nothing
    
    End Sub
The VBA Code Line By Line.
Before running the Code, let us take a look at each line and see what it does.
The first line declares Arr as a ClsArea object. The next line declares it ObjColl as an Collection object and Obj as a generic Object type. The following line declares two integer-type variables, and the line after that declares a String variable.
The iMax variable is initialized with the value 5 to control the For...Next loop. We will create five ClsArea objects, assign their property values, and then add them one by one to the Collection object.
Next, the ObjColl collection object is instantiated in memory.

A For...Next loop is then set up to run from 1 to iMax (or 5). Within the loop, it Arr is instantiated as a new ClsArea class object in memory, ready to receive its first set of property values. The room description will be created by combining the constant text "Bedroom" with the loop control variable j, resulting in room names from "Bedroom1" to "Bedroom5".
Similarly, the dblLength property value of each room will be set to 20 + j (resulting in values from 21 to 25), and the dblWidth property will be set to 15 + j (resulting in values from 16 to 20).
After assigning the property values to Arr, the class object is added to the ObjColl collection using the Add method.
The statement Set Arr = Nothing then releases the current class object from memory.
The For...Next loop continues this process to create and add four more ClsArea objects to the collection.

Next, another For ... Next loop in the printing section uses the Obj object variable to iterate through each item in the collection and print the ClsArea object property values in the Debug Window.

  • Click somewhere in the middle of the Code.
  • Press CTRL+G to display the Debug Window.
  • Click somewhere in the code and press the F5 Key to run the Code.
  • The output in the debug window will be as shown below:

    Description   Length        Width         Area
    Bed Room1      21            16            336 
    Bed Room2      22            17            374 
    Bed Room3      23            18            414 
    Bed Room4      24            19            456 
    Bed Room5      25            20            500 
    

    We have not provided the second parameter (Key value) in the above example. In the printing section, an object variable is used to retrieve each ClsArea class object from the Collection in the same order in which they were added, and then print their property values in the Debug Window.

    The following code snippet can be used as a replacement in the above program to retrieve each item from the Collection object. This version uses the item’s sequence number as a parameter to the Item method to fetch each object, preserving the order in which they were added to the collection.

    'Printing Section
    Debug.Print "Description", "Length", "Width", "Area"
    For j = 1 To objColl.Count
        With objColl.item(j)
            Debug.Print .strDesc, .dblLength, .dblWidth, .Area
        End With
    Next
    

    The number of items in the collection is determined by the expression ObjColl.Count in the For... Next loop.

    You may insert a Stop statement above the printing section and run the code. When the program pauses at the Stop statement, open the Locals Window from the View menu.

    Click the plus symbol [+]ObjColl to expand it and display the ClsArea object items stored within the collection.

    Next, click the plus symbol [+]Item 1 to expand the first item and view its ClsArea object properties and their current values.

    Notice that the dblLength property value is shown as 21. We will now attempt to change this value by typing an expression directly in the Immediate (Debug) Window.

    Type the following expression in the Debug Window and press Enter:

    ObjColl.Item(1).dblLength = 50

    Check the Locals Window now — you will see that the value 21 has changed to 50. This demonstrates that you can overwrite the property values of an object already stored in the collection. However, you cannot directly replace the object item itself in the collection.

    If you want to replace an entire object item, you must first remove the existing item from the collection by specifying its sequence number as a parameter (for example: ObjColl.Remove 1). Then, create a new object with the required changes and add it back to the collection.

    To place the new item back in the same position where the old item was removed, you can use the Before or After parameter of the Add method along with the appropriate item number.

    For more details, refer to last week’s article “MS-Access and Collection Object Basics” for a clear explanation of the Before and After parameter usage of the Add method.

    Save to Collection with Key.

    Let us try another example by making a few changes to the previous code. This time, we will add items to the Collection Object using Key values. In the printing section, we will retrieve the ClsArea Class Object items from the Collection by referencing their Key values instead of their index numbers.

    Copy and Paste the following Code into a Standard Module:

    Public Sub Coll_TestTwo()
    
    Dim Arr As ClsArea
    Dim objColl As Collection
    Dim j As Integer, obj As Object
    Dim iMax As Integer
    Dim Desc As String, strKey As String
    
    iMax = 5
    'instantiate Collection Object
    Set objColl = New Collection
    
    For j = 1 To iMax
    'instantiate a temporary ClsArea Object
        Set Arr = New ClsArea
        
        Desc = "Bed Room" & j
     'Assign Property Values
        Arr.strDesc = Desc
        Arr.dblLength = 20 + j
        Arr.dblWidth = 15 + j
        
       On Error Resume Next
    'Validate Collection Key, ClsArea Object with the same Key exists or not
       Set obj = objColl.Item(Desc)
       
       If obj Is Nothing Then ' doesn't exists, Add the ClsArea Instance
          objColl.Add Arr, Desc 'Add Item to Collection with KEY parameter
       Else
          MsgBox "Error: " & Desc & " Already Exists."
       End If
       
       On Error GoTo 0
       Set Arr = Nothing 'release temporary ClsArea Object
    Next
    
    'Print items in reverse order
    Debug.Print
    For j = objColl.Count To 1 Step -1
        strKey = "Bed Room"  & j
        
        Set obj = objColl.Item(strKey) 'access items with KEY value
      
        With obj
             Debug.Print .strDesc, .dblLength, .dblWidth, .Area
        End With
    Next
    
    Set objColl = Nothing
    End Sub 

    We have introduced two additional String variables, including Desc, to store the item description for the ClsArea object’s Arr.strDesc property. This same description will also serve as the Key value in the Add method.

    The strKey variable will be used when retrieving each ClsArea object from the Collection by its key. Although we could reuse the Desc variable for this purpose, we use a separate strKey variable for better clarity.

    The statement objColl.Add Arr, Desc adds the ClsArea object instance Arr to the Collection, using the description (for example, "Bedroom1") stored in the Desc variable as the key for this first item.

    Other Syntax variants of the above statement are given below for reference.

    objColl.Add item:=Arr, key:=Desc 'statement with Parameter Names
      'OR
    objColl.Add key:=Desc, item:=Arr 'values in improper order with Parameter Names
      '
    1. In the printing section, we have arranged the For ... Next loop to run in reverse order, retrieving items from the Collection by their Key values—starting from "Bed Room5" down to "Bed Room1".

      The statement Set ObjColl = Nothing is used to clear the Collection object from memory.

      However, there are a few limitations when using Key values with a Collection object:

      It accepts only the String data type as a Key value.

    2. Once the Key Value is assigned to a Collection item, you cannot retrieve the Key value itself or create a list of the Keys from the Collection Object.

    3. If you already know the Key Value (like Employee Code), you can retrieve the actual Object Item belonging to that Key from the Collection.

    4. If you attempt to add an Item with an existing Key Value in the Collection, it will trigger an Error.

    A better alternative is the Dictionary object, which provides greater flexibility for storing and retrieving items or values compared to the Collection object.

    We will explore and experiment with the Dictionary Object and its methods next week.

    CLASS MODULES.

    1. MS-Access Class Module and VBA
    2. MS-Access VBA Class Object Arrays
    3. MS-Access Base Class and Derived Objects
    4. VBA Base Class and Derived Objects-2
    5. Base Class and Derived Object Variants
    6. Ms-Access Recordset and Class Module
    7. Access Class Module and Wrapper Classes
    8. Wrapper Class Functionality Transformation

    COLLECTION OBJECT.

    1. Ms-Access and Collection Object Basics
    2. Ms-Access Class Module and Collection Object
    3. Table Records in Collection Object and Form

    DICTIONARY OBJECT.

    1. Dictionary Object Basics
    2. Dictionary Object Basics-2
    3. Sorting Dictionary Object Keys and Items
    4. Display Records from Dictionary to Form
    5. Add Class Objects as Dictionary Items
    6. Update Class Object Dictionary Item on Form
    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