Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

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:

    No comments:

    Post a Comment

    Comments subject to moderation before publishing.

    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