Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Table Query Records in Collection Object

Class Module and Collection Object.

  1. Create a Data View Form with selected Fields from a Table or Query using the built-in Access Form Wizard.
  2. Create a ComboBox, on the Header of the Form, using any of the Fields, like [Last Name] having unique values from the Record Source Table/Query. The ComboBox values will be used as the Record Key to retrieve the selected record randomly from the Collection Object and displays it in the unbound TextBoxes.

  3. Create an unbound TextBox with the name KeyField, in the Header of the Form,  and set its Visible Property value to False. Write the expression  ="[Last Name]" in the TextBox, if the [Last Name] Field data is in the ComboBox. If the Last Name field alone will not provide unique values then create a Query using Employees Table and join First Name and Last Name Fields in an expression, use a suitable Column Name, use the Query for the Form, and the new Field Values for the ComboBox on the Form. 
  4. Create a Command Button in the Footer of the Form with the Name cmdClose and the Caption Close.

  5. Copy the Form1 Module Code (from the attached Demo Database) and Paste it into the Module of the newly created Employees Form's Module.
  6. Save the Form and Close it.

The Form runs the ready-made VBA Code in the DATA_View Class Module. The Class Module is reusable for Forms created in this manner with any Table/Query as Source Data. No need to make any changes.

Open the Form in Normal View and select an item from the ComboBox the record with that Key value will be retrieved from the Collection Object and displayed in the unbound Textboxes on the Form instantly. This Form is intended for data view purposes only. The TextBoxes are locked and the data cannot be edited.

How much time it takes to create the above Form with the simple steps explained above. You don't have to write any Code on the Form Module. The TextBoxes are placed properly by the Form Wizard. Hardly it takes about 5 minutes to prepare the Data View Form and ready to run with the Data_View ready to run Class Module. 

The Ready-made Reusable Form Module Code:

Option Compare Database
Option Explicit

Private Cls As New DATA_View

Private Sub Form_Load()
Set Cls.o_frm = Me
End Sub

Private Sub Form_Unload(Cancel As Integer)
  Set Cls = Nothing
End Subc

The DATA_View Class Object is instantiated in the Employees Form Module and the current Form Object is assigned to the o_Frm() Property of DATA_View Object.

The Ready-made Reusable DATA_View Class Module Code.

Option Compare Database
Option Explicit

Private WithEvents cbo As ComboBox
Private WithEvents cmd As CommandButton
Private oFrm As Form
Private frmSec As Section

Private Coll As New Collection
Private txtBox() As String
Private strTable As String

'------------------------------------------------------
'Streamlining Form Module Code
'in Stand-alone Class Modules
'With Reusable Code
'------------------------------------------------------
'Quick Data View Screen
'Saving Table/Query Records in Collection Object
'Author:  a.p.r. pillai
'Date  :  26/04/2024
'Remarks: Keep Recordset in Collectuon Object
'       : and Retrieve specific record using Key
'Rights:  All Rights(c) Reserved by www.msaccesstips.com
'------------------------------------------------------

Public Property Get o_frm() As Form
    Set o_frm = oFrm
End Property

Public Property Set o_frm(ByRef vfrm As Form)
    Set oFrm = vfrm
    
    Set frmSec = oFrm.Section(acDetail)
    Call Class_Init
End Property

Private Sub Class_Init()
Dim db As Database
Dim rst As Recordset
Dim flds As Integer
Dim ctl As Control
Dim k As Integer
Dim Rec() As Variant, strKey As String
Dim vKeyName As String

strTable = oFrm.RecordSource

Set cmd = oFrm.cmdClose
    cmd.OnClick = "[Event Procedure]"
    
Set cbo = oFrm.cboName
cbo.OnClick = "[Event Procedure]"

'Make the Data Field TextBoxes Unbound
'Save the Field Names on the Form into the txtBox() Array
flds = 0
For Each ctl In frmSec.Controls
    Select Case TypeName(ctl)
        Case "TextBox"
           ctl.ControlSource = ""
           flds = flds + 1
           ReDim Preserve txtBox(1 To flds) As String
           
'Get the selected Field Names from the
'TextBoxes on the Form's Detail Section
           txtBox(flds) = ctl.Name
           ctl.Locked = True
    End Select
Next
'Set ComboBox Default Value
'Change Form Properties
oFrm.cboName.DefaultValue = "=[cboName].[column](0,0)"
oFrm.RecordSelectors = False
oFrm.NavigationButtons = False
oFrm.ScrollBars = 0

'Load the Table/Query Records into Collection Object
ReDim Rec(1 To flds) As Variant

Set db = CurrentDb
Set rst = db.OpenRecordset(strTable, dbOpenSnapshot)

'------------------------------
vKeyName = oFrm!KeyField 'Collection Key Field Value
'------------------------------

Do While Not rst.EOF
    For k = 1 To flds
       Rec(k) = rst.Fields(txtBox(k)).Value
    Next

'Key Field Name in the Form Fields
'=========================================
   strKey = rst.Fields(vKeyName).Value
'=========================================
    Coll.Add Rec, strKey 'Save Rec() Array
    rst.MoveNext
Loop

Set rst = Nothing
Set db = Nothing

End Sub

Private Sub cbo_Click()
Dim strKy As String, Record As Variant
Dim j As Long, L As Long, H As Long

'Get Selected Collection Key from ComboBox
strKy = cbo.Value
 
'Retrieve the record using Key from Collection
'and load into Variant Array Record
  
  Record = Coll(strKy)
  
  L = LBound(Record)
  H = UBound(Record)
  
'Add Field Values into corresponding Text Boxes
  For j = L To H
    oFrm(txtBox(j)) = Record(j) 'Display in Unbound TextBox
  Next
  oFrm.Requery
  
End Sub

Private Sub cmd_Click()
    DoCmd.Close acForm, oFrm.Name
End Sub

Private Sub Class_Terminate()
Do While Coll.Count > 0
    Coll.Remove 1
Loop

End Sub
Records in Collection Object

Data_View VBA Code Segment-wise Review.

Note: You can Instantiate this single Data_View Class Module in several such data display Form Modules, in the same Project, and keep all of them open together, if necessary, and work with them. No need to duplicate the Class Module or VBA Code.

The Global Declarations.

The ComboBox and Command Button Controls are declared with the Keyword WithEvents to capture Events when fired from these objects on the Form. In the next two lines, a Form Object oFrm and a Form Section Object are declared.

The Collection Object is Instantiated with the object name Coll followed by the txtBox() Array, with unspecified elements of String Type, and the string Variable strTable for saving the Form Record Source (Table/Query) name from the Form.

The next segment is the Form Get and Set Property Procedures to capture the active Form Object Value passed from the Form_Load() Event Procedure of Employees Form. In the Set Property Procedure after assigning the Form Object received in vFrm Parameter to the oFrm Property the Employees Form Detail Section Reference is assigned to the frmSec Object and then calls the Class_Init() Subroutine.

At the beginning of the Class_Init() Subroutine the statement:

strTable = oFrm.RecordSource

reads the Form's Record Source Property value and retains it in the srtTable Variable.

The Command Button and Combobox Object References from the Form are assigned to the cmd and cbo Objects respectively and are enabled with the Click Events too.

'Make the Data Field TextBoxes Unbound
'Save the Field Names on the Form into the txtBox() Array
flds = 0
For Each ctl In frmSec.Controls
    Select Case TypeName(ctl)
        Case "TextBox"
           ctl.ControlSource = ""
           flds = flds + 1
           ReDim Preserve txtBox(1 To flds) As String
           
'Get the selected Field Names from the
'TextBoxes on the Form's Detail Section
           txtBox(flds) = ctl.Name
           ctl.Locked = True
    End Select
Next
'Set ComboBox Default Value
'Change Form Properties
oFrm.cboName.DefaultValue = "=[cboName].[column](0,0)"
oFrm.RecordSelectors = False
oFrm.NavigationButtons = False
oFrm.ScrollBars = 0

The For . . . Next Loop scans the Detail Section of the Form for the TextBox Control names (or the actual Source Data Field Names) and loads them into the txtBox() Array and calculates the number of TextBox Controls on the Form in Flds Variable. The ctl.ControlSource = "" makes the TextBoxes Unbound. The txtBox() Array is redimensioned at each level increasing the array element by 1, preserving the data of earlier elements, and taking the count of fields in the Flds Vriable. This method automatically adjusts to the number of Fields added/deleted from the Form by the user at will. 

The ComboBox's default Value is set with the Statement: =[cboName].[column](0,0).

The next four statements change the Form Properties.

vKeyName = oFrm!KeyField

The above statement reads the KeyField Name given in the expression like  ="[Last Name]" and assigns it to the Variable vKeyName. The Collection Object Key must be a Field with unique data, and the same Field data must appear in the ComboBox cboName.  The ComboBox item will be used to retrieve the Record from the Collection Object randomly.

ReDim Rec(1 To flds) As Variant
Set db = CurrentDb
Set rst = db.OpenRecordset(strTable, dbOpenSnapshot)

'----------------------------
vKeyName = oFrm!KeyField
'----------------------------

Do While Not rst.EOF
    For k = 1 To flds
       Rec(k) = rst.Fields(txtBox(k)).Value
    Next

'Key Value Field Name in the Form Fields
'=========================================
   strKey = rst.Fields(vKeyName).Value
'=========================================
    Coll.Add Rec, strKey
    rst.MoveNext
Loop

The Rec() Array is redimensioned for the number of Data Fields on the Form. These field values are read from the Source Table/Query, one record at a time, the Rec() Array elements are filled with the Field values and the Rec() Array is added as a single Item in the Collection Object, with the Last Name Field as Collection Item Key, the second parameter of the Collection Object's Add() Method. In this way, all the Source Data Records are loaded into the Collection Object in Memory.

Note: The Source Table/Query may have many more fields of data than what you originally placed on the Form with the Form Wizard. The Program will read data based on the Field Names appearing on the Form only, other fields in the Source Table/Query are ignored. You may add more Fields to the Form or Delete some of them at your will at any time. You may rearrange the Fields the way you like but see that their Name Property Value is not changed and matches with a Field in the Record Source Table or Query. No need for any change in the VBA Code. 

The cbo_Click() Event Subroutine.

Private Sub cbo_Click()
Dim strKy As String, Record As Variant
Dim j As Long, L As Long, H As Long

'Get Selected Collection Key from ComboBox
strKy = cbo.Value
 
'Retrieve the record using Key from Collection
'and load into Variant Array R
  
  Record = Coll(strKy)
  
  L = LBound(Record)
  H = UBound(Record)
  
'Add Field Values into corresponding Text Boxes
  For j = L To H
    oFrm(txtBox(j)) = Record(j)
  Next
  oFrm.Requery
  
End Sub

When the User selects an Item from the Combobox the selected value is used as the Collection Object Item Key to retrieve the Item and loads it into Record() Array.

The Record Array Element values are read in the order they are loaded into memory and the unbound TextBox Values are filled in the order their names are read from the Form earlier. The TextBoxes are in the locked state and their contents cannot be changed. 

The Data_View Class Module and the Form Module Code can be used for any such Forms created using the same Procedure for Data View without any change. See that the ComboBox Name is cboName and the CommandButton Name is cmdClose.

Data Field Names will be picked from the TextBox's Name Property, created through the Form Wizard, in the Detail Section of the Form.

Creates a Data View Form in Minutes, with ready-to-use Code.


Demo Database Download


  1. Reusing Form Module VBA Code for New Projects.
  2. Streamlining Form Module Code - Part Two.
  3. Streamlining Form Module Code - Part Three
  4. Streamlining Form Module Code - Part Four
  5. Streamlining Form Module Code - Part Five
  6. Streamlining Form Module Code - Part Six
  7. Streamlining Form Module Code - Part Seven
  8. Streamlining Form Module Code - Part Eight
  9. Streamlining Form Module Code - Part Nine
  10. Streamlining Form Module Code - Part Ten
  11. Streamlining Form Module Code - Part Elevan
  12. Streamlining Report Module Code in Class Module
  13. Streamlining Module Code Report Line Hiding-13.
  14. Streamlining Form Module Code Part-14.
  15. Streamlining Custom Made Form Wizard-15.
  16. Streamlining VBA Custom Made Report Wizard-16.
  17. Streamlining VBA External Files List in Hyperlinks-17
  18. Streamlining Events VBA 3D Text Wizard-18
  19. Streamlining Events VBA RGB Color Wizard-19
  20. Streamlining Events Numbers to Words-20
  21. Access Users Group(Europe) Presentation-21
  22. The Event Firing Mechanism of MS Access-22
  23. One TextBox and Three Wrapper Class Instances-23
  24. Streamlining Code Synchronized Floating Popup Form-24
  25. Streamlining Code Compacting/Repair Database-25
  26. Streamlining Code Remainder Popup Form-26
  27. Streamlining Code Editing Data in Zoom-in Control-27
  28. Streamlining Code Filter By Character and Sort-28
  29. Table Query Records in Collection Object-29
  30. Class for All Data Entry Editing Forms-30
  31. Wrapper Class Module Creation Wizard-31
  32. wrapper-class-template-wizard-v2
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