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

Microsoft TreeView Control Tutorial

A. Microsoft TreeView Control Tutorial.

The Microsoft TreeView Control, part of the Microsoft Windows Common Controls library, is a powerful component for displaying related data in a hierarchical node structure. It can represent information such as index entries and subentries, folder structures similar to the left pane of Windows Explorer, or any collection of related items, complete with tree lines, checkboxes, and graphical icons.

In addition to the TreeView Control, we will also use the ListView and ImageList controls, which are part of the Microsoft Windows Common Controls ActiveX library, to enhance functionality and visual presentation within Microsoft Access applications.

In the coming weeks, we will explore how to design, build, and customize a TreeView Control from scratch. As a preview of the concepts and implementations we will cover, I will also share several TreeView demonstration images illustrating the final results we will be working toward.

B. Sample Demo Images.

      Nodes in the Collapsed state.

  1. The Sample Demo TreeView Image with all Nodes in Collapsed form.

     Nodes in the Expanded View.

  2. The TreeView Control Nodes are in the expanded view.

    With Arrowhead Image Icons.

  3. The TreeView Sample Display, with arrowhead Image Icons displayed to the left of each Node Text.

    Folder Images for root-level nodes; others with arrowheads.

  4. Next, we will examine a TreeView display integrated with related data presented in a subform. The root-level nodes are visually enhanced in two graphical states: a closed folder icon in the default state and an open folder icon when selected. Selecting a root-level node changes its icon and also automatically expands the node to display its associated child nodes.

    The subform dynamically updates to display information related to the selected root-level node. Additionally, selecting specific child nodes can trigger another Form display, which is normally kept hidden, to present additional related details when needed. 

    TreeView and ListView Controls.

  5. In the next Form layout, there are two panels. The left panel contains the TreeView control, which displays nodes representing product categories. When you select the Category node, the right panel with the ListView Control updates to display the related product items, along with their quantities and list prices in separate columns.

C. Creating Sample Data for Trial Run.

Let us try the TreeView Control with the sample data below, based on the first two images shown at the beginning of this Page.

The sample data table contains three fields:

  1. ID – An AutoNumber field that generates unique ID numbers. AutoNumber is used here for convenience, but regardless of the data type, each table record must have a unique ID value. If the ID is numeric, it must be converted to a string (with at least one alphabetical character) before adding it to the TreeView control.

  2. Description (Desc) – Contains the node descriptions. The entries in this column are logically related to one another.

  3. ParentID – A numeric field that identifies the parent node for each record. This value should be changed to String type before using it in the TreeView control.

To build the hierarchy, we need to understand the relationship between records. The description values are related to each other. Based on the relationship, the related Record ID is updated in the ParentID field.

For example, the logical hierarchy could represent:

  • Authors → Publishers → Bookstores where the books are sold.

  • Members of a family tree.

  • Product categories → Products → Stock → Price.

This related information may not always exist in a single column or table—it could be spread across multiple columns or even different tables.

The ParentID field plays a crucial role in defining the hierarchical arrangement of nodes. If the ParentID field is empty, the record is treated as a root-level node. A child node must always have its ParentID Field populated with the parent record ID.

A root-level node can have one or more child nodes, and a child node can, in turn, have its own child nodes, creating multiple hierarchy levels.

First, we will load the sample data into a TreeView control to view its initial arrangement. Then, by filling in the ParentID field with related IDs, we can reorganize the nodes into the desired logical order.

D. Windows Common Controls Library File.

  1. First, open an existing database or create a new one.
  2. Press ALT + F11 to open the VBA editor, then choose References… from the Tools menu.
  3. In the list of available references, look for Microsoft Windows Common Controls and select it.

    • If the file is not listed, click Browse… and locate MSCOMCTL.OCX in the Windows system directory.

    • In Windows 7 (64-bit), you will typically find it in the SysWOW64 folder.

    • Select it, then click OK to close the References dialog.

  4. Create a Table with the following structure:

    Right-click to open the Large Image in a New Window.

  5. Name the Table as Sample and save it.

  6. Add about twelve records in the Table, as shown in the data view Image above. 

    E. Creating TreeView Control on Form

  7. Create a New blank Form.

  8. Click on the ActiveX Controls button from the Controls Group, find the Microsoft TreeView Control, then select it.

  9. Click OK to insert a TreeView control on the Form.

  10. Drag the TreeView control slightly down and to the right to leave some space along the top and left edges.

    Next, use the bottom-right sizing handle to stretch the control down and to the right, enlarging it to match the proportions shown in the sample image below.

  11. Display the control's Property Sheet and change its Name Property Value to TreeView0.

  12. Display the VBA Editing Window of the Form.

  13. F. Access VBA Code.

  14. Copy and paste the following VBA Code into the Module, overwriting the existing lines of code there:
    Option Compare Database
    Option Explicit
    
    Dim tv As MSComctlLib.TreeView
    Const KeyPrfx As String = "X"
    
    Private Sub Form_Load()
    Dim db As Database
    Dim rst As Recordset
    Dim strSQL As String
    Dim nodKey As String
    Dim ParentKey As String
    Dim strText As String
    
    Set tv = Me.TreeView0.Object
    
    strSQL = "SELECT ID, Desc, ParentID FROM Sample;"
    
    Set db = CurrentDb
    Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)
    
    Do While Not rst.EOF And Not rst.BOF
        If Nz(rst!ParentID, "") = "" Then
            nodKey = KeyPrfx & CStr(rst!ID)
            strText = rst!Desc
            ‘Add the TreeView Root Level Nodes
            tv.Nodes.Add , , nodKey, strText
        
        Else
            ParentKey = KeyPrfx & CStr(rst!ParentID)
            nodKey = KeyPrfx & CStr(rst!ID)
            strText = rst!Desc
            ‘Add the Record as Child Node
            tv.Nodes.Add ParentKey, tvwChild, nodKey, strText 
            
        End If
        rst.MoveNext
    Loop
    rst.Close
    
    Set rst = Nothing
    Set db = Nothing
    
    End Sub
    
    
  15. Save the Form with the name frmSample, but don’t close the VBA Window.

    G. VBA Code Review – Line by Line

    Let’s take a quick look at the VBA code and understand what it does.

    In the Global Declaration area of the Form module:

    • tv is declared as a TreeView object.

    • KeyPrfx is declared as a String constant with the value "X".

    The TreeView Node’s Key must always be a string and must contain at least one non-numeric character. Since our sample table’s key values are purely numeric, we convert them to strings and prefix them with the letter "X".

    • Example: 1 → "X1"

    • Simply converting a numeric value to a string (without an alphabet) will not be accepted as a valid Node key.

    Note: If the Node Key and Parent Key are already in alphabetic or alphanumeric form, conversion is unnecessary. All Node keys must still be unique.


    In the Form_Load() event procedure:

    1. Database and Recordset objects are declared, along with four string variables.

    2. The statement:

      Set tv = Me.TreeView0.Object

      assigns the TreeView0 control on the form to the object variable tv.

    3. OpenRecordset() Opens the sample table records using the SQL string strSQL.

    4. The Do While...Loop ensures the recordset is processed only if it is not empty; otherwise, the loop exits and the procedure ends.


    Determining Node Type

    • If the ParentID field is empty, the record becomes a Root-level Node.

      • A Root Node needs only a unique Key and Text (from the ID and Desc fields).

    • If the ParentID field has a value, then the record becomes a Child Node of either a Root Node or of an upper-level Child Node.


    Building the Node Key & Text.

    • nodKey is created by converting the ID field to a string and prefixing it with "X". Example: ID = 1 → nodKey = "X1".

    • strText stores the Desc field value. This keeps the Nodes.Add() parameters short and readable, especially when field references are long.


    Adding the Node

    The statement:

    tv.Nodes.Add(...)

    calls the Add() method of the TreeView’s Nodes collection to insert the node into TreeView0 on frmSample.


    Syntax of Add() method:

    tv.Nodes.Add([Relative], [Relationship], [Key], [Text], [Image], [SelectedImage]) As Node
    • All six parameters are optional.

    • Calling it without parameters adds an empty Root Node (a blank tree line).

    Requirements:

    • Root Node: Needs only Key and Text.

    • Child Node: Requires both [Relative] and [Relationship].

      • Omitting either adds it as a Root Node (no error occurs).

      • [Relative] is the Node Key of the existing parent (from ParentID).

      • [Relationship] is the constant tvwChild (value 4), identifying it as a child of the parent node.

The other constant values for the relationship arguments determine the child node's specific positions. The Constant Values are as follows:

tvwFirst = 0,  places as the first Node, at the level of the relative Node.

tvwLast = 1,  places as the last Node, at the level of the relative Node.

tvwNext = 2,  places the Node after a specified Node.

tvwPrevious = 3, places the Node immediately preceding the specified Node.

Note: You can experiment with different values in the Relationship argument and run the code in Debug Mode, keeping the VBA editor and the form in Normal View side by side. Observe how the nodes are arranged during each iteration of the code. This will help you understand the effect of each relationship type.

This is useful when editing the TreeView—such as deleting an item, inserting another item in its place, or adding a new node at a specific location.

A node referenced in the [Relative] argument must already exist in the Nodes collection before you can add a child node to it. Otherwise, it will generate an error.

The process continues until all records in the recordset have been processed.

Note: You may need to review the VBA code again after running the demo to reinforce your understanding.

H. The First Trial Run.

Open the Form in Normal View.  The Trial Run result looks like the Image given below.

It doesn’t look much different from a regular ListBox at this moment. This is because we have not yet assigned any values in the ParentID field in our sample table. To arrange items hierarchically in the TreeView control, we must define relationships between the rows in the table.

I. Understanding the Relationship Between Records

Open the sample table and examine how the records are related to each other.

We will keep the Database item as a root node. The database object also contains several top-level objects—Application, DBEngine, Workspaces collection, and Databases collection—which we have not included here.

Next, we have the Tables group item with ID value 2.

In the following records, we see the Table, Fields collection, and Field item, which are related to the Tables group. Our goal is to place the Table, Fields, and Field records under the parent node Tables (ID value 2).

In this hierarchy, the Tables record is the parent node, and the Table, Fields, and Field records are the child nodes.

J. Updating the ParentID Field

To achieve this structure, need to update the ParentID field value to 2 for the Table, Fields, and Field records (the node key of Tables).

Update only these records, then close the table. Once completed, your records should look like the example shown in the image below.

Now, open frmSample in Form View and check the TreeView control.
At first glance, the display will look exactly the same as before—no visible changes.
However, the updates you made are already in effect; they’re just not reflected visually yet.

K. The TreeView Control Property Sheet. 

The TreeView control has its own Property Sheet, and these settings influence how the control appears. We’ll adjust one of these properties before returning to the TreeView to see the change.

  1. Switch frmSample to Design View.

    1. Right-click the TreeView control.

    2. From the shortcut menu, highlight TreeCtrl_Object and select Properties.

    3. The Property Sheet now appears, as shown below.

    4. The Settings on this Property Sheet change the appearance of the TreeView Display.

      The top-left Property Style has already selected Option 7 (tvwTreeLinesPlusMinusPictureText), the maximum features available.

    5. Change the LineStyle Property Value = 1 (tvwRootLines) and click the Apply button, then click OK to close the Property Sheet.

      L. Running After the LineStyle Property Change

    6. Save the form and open it in Normal View.
      You’ll now see the tree lines displayed correctly.

    7. The Tables node now shows a plus (+) sign. The plus symbol indicates that there are Child Nodes to view.

      • Click the plus (+) sign to expand the node and reveal all child nodes sharing the same ParentID.

      • Click the minus (–) sign to collapse them again, hiding the child nodes and changing the symbol back to a plus (+).

      When expanded, the display will resemble the image shown below:

      Updating the ParentID for Other Records.

      Next, we will establish the parent–child relationships for the remaining records.

      1. Forms and Controls

        • Update the ParentID field of the Form, Controls, and Control records with the Forms item's ID value (Node-Key).

        • This ensures these records will appear under the Forms node as its child nodes in the TreeView.

      2. Reports and Controls

        • Similarly, update the ParentID field of the Report and Control records with the Reports record’s ID value (Node-Key).

        • This positions them under the Reports node as its child nodes.

    8. Once the updates are complete, your Sample Table should match the ParentID values shown in the illustration below:

      After implementing the above changes, open the form and expand all the nodes in the TreeView. The display should now resemble the image shown below, with every parent node and its corresponding child nodes fully visible.

      All child nodes related to the root-level nodes—Tables, Forms, and Reports—are grouped under their respective parent nodes. However, a child node may also have a parent, a grandparent, or even a great-grandparent node, depending on the hierarchy.

      N. Arranging All Objects in a Logical Hierarchical Order
      Let’s take the first root-level node, Tables, as an example. Logically:

      • Field (record ID 5) is directly related to the Fields collection (record ID 4).

      • The Fields collection is related to the Table.

      • The table is part of the Tables collection.

      This means that each item in the group (record numbers 5 through 2) is related to the step above it in the hierarchy.

      Next, we will position these child nodes under their respective parent nodes in the correct order and see how the arrangement appears in the TreeView control.

    9. Open your Sample Table and change the ParentID values of the Tables related to Child Records as shown below:

    10. The record Field with ID 5 has Field (record ID 4) as its parent. Therefore, update the record ID 5's ParentID field value to 4.

      Similarly:

      • Record 4 (Field) has record 3 (Table) as its parent, so we set its ParentID to 3.

      • Record 3 (Table) has record 2 (Tables) as its parent, so we set its ParentID to 2.

      Note: The records do not have to appear next to each other in the table to establish this hierarchy.

      After making these changes, save the table and open frmSample to view the results. Your TreeView display should now resemble the image shown below, with all nodes expanded.

    The Root-level Reports Node has two Child Nodes: 1. Report,  2. Controls. The Controls group Item can logically be a child Node of the Report Node. So, it can be placed into a child node position of the Report Node. Individual Controls, similar to TextBoxes and Labels, can be Child Nodes of the Controls Parent Node.  This way, it can go several steps down the tree.

    Change the other two groups' child nodes' ParentID field values.  When you do that correctly, it will look like the image given above.

    Download TreeView Demo Database.


    DICTIONARY OBJECT

    1. Dictionary Objects Basics
    2. Dictionary Object Basics-2
    3. Sorting Dictionary Object Keys and Items
    4. Display Records from Dictionary
    5. Add Class Objects as Dictionary Items
    6. Update Class Object Dictionary Item
Share:

Word Mail-Merge with Ms-Access Table

Word Mail Merge with MS Access Table.

Form Letters.

Form letters are prepared from a standard Microsoft Word template, with addressee-specific information inserted into each letter. Appointment letters, interview call letters, employment contracts, and similar documents are typical examples. Preparing such letters using Microsoft Word’s Mail Merge feature is much easier than composing each letter individually for every addressee.

These types of letters contain common body text that applies to all recipients, along with specific areas where personalized information can be inserted, such as the recipient’s Name and Address, interview date, or the nearest location where a candidate can attend the interview.

If interview call letters need to be sent to hundreds of prospective candidates, we need to prepare only a single template letter containing the standard body text applicable to all recipients. Other personalized information can then be automatically inserted from the associated data table at the appropriate locations in each letter during printing. In Microsoft Word, this process is known as Mail Merge.

We have already tried to replicate this process in Microsoft Access using VBA some time ago. The links to those posts are provided below for your reference:

  1. MS Access and Mail-Merge
  2. MS Access and Mail-Merge-2
  3. MS Access and Mail-Merge-3

The Names, Addresses, and other related information of each individual can be kept in a data table.  The external Table can be prepared in any of the following Applications:

  1. MS Word Document with Table Grid.
  2. MS Excel Data Table.
  3. MS Access Table.

The Table can be linked to the Form Letter so that MS Word can pick the required information from the Table and insert it where table field codes are placed in the body of the letter.

Sample MS Word Table.

We have prepared a small Table in an MS Word Document within the Table Grid, as an example in case you prefer to prepare one in Microsoft Word itself.  Here is an image of the data table with only 3 entries, similar to the one in the Northwind Employees Table.

Click on the Image to Enlarge.


MS Access Employees2 Table.

But we will be using a modified Employees Access Table prepared with a few new fields for our Mail Merge Demo Run, taken from the original Employees Table in the Northwind sample database.  The  image of the Employees2 Access Table is given below:

Click on the Image to Enlarge.

Create the Employees2 Table from the Northwind Employees Table, with the selected fields in your Database.  Create three more fields and fill them with sample data as shown in the above image.

Sample Letter Specimen.

A Specimen image of the Letter, without the individual Employee details, is given below:

Click the Image to enlarge it.

Create a Letter in Microsoft Word similar to the specimen above, and save it as Employees.

Sample Merge-Printed Letter.

When we merge-print the personal information in the Document, from the Access Table, it will look like the sample image given below:

Click the Image to Enlarge.

Inserting the Merge Fields in the Document.

Let us prepare a Mail-Merge Document in MS Word, using the Employees2 Table as Source Data,  matching the above-merged letter model. 

We assume that the above employees of our organization are awarded an annual increment in recognition of their commendable contributions to the company’s overall growth and to encourage them to perform better by taking on future challenges. 

  1. Open the Employees Word Document, as per the above specimen, created and saved earlier.  If you have not yet created one, let us do it now.

  2. Click on Start Mail-Merge from the Mailings Menu and select Letter.

  3. Click on Select Recipients and select Use Existing List.

  4. Find the Database where you saved the Employees2 Table and click Open.

  5. The list of Tables is displayed; select the Employees2 Table, and click OK to select it, and the Employees2 table is attached to the Document.

  6. Next, click Edit Recipient List to display all records in the Employees2 table. A checkmark indicates that an employee record is selected for inclusion in the merged letters. If an employee should be excluded from the letters, clear the checkmark for that record.

    First, we will insert the Address Block and Greeting Line information into the letter using the Merge Fields selected from the attached table. Although these elements can be inserted in two simple steps using the automatic options, we will take a more manual approach to customize the output and avoid complications if the automatic method is not fully understood by the first-time user. You can try the automatic method later by selecting the Address Block and Greeting Line buttons and experimenting with their available options to modify the document output.

  7. Click below the Reference information (Ref: ABC/HRD/2020/1234-) and above the word Dear on the Letter.

  8. Click on the Insert Merge Field option in the Mailings Menu and click on the First Name Field.  Open the same list again and select the Last Name.

  9. Click in the middle of both field codes and tap the space bar to insert a space between the FirstName and LastName segments of the Employee Name and position the insertion point on the following line.

  10. Select Address from the Merge-Field list for the second line.

  11. Select City for the third address line.

  12. Insert State/Province and Country/Region on the next line, with a space in between.

  13. Position the insertion point after the word Dear with a space, and insert the First Name and Last Name fields with a space in between.

    After inserting the merge fields, it will look like one of the images below, based on the Field-Code display option setting ALT+F9.

    OR

    The second image is the expanded form of Merge Field Codes. You can toggle between these two states by pressing ALT+F9.  See that the Preview Result button is in the deselected state.  If the Preview Result button is active, then the actual data will be displayed.

  14. Position the insertion point on the Designation line and insert the Job Title merge field.

  15. On the next three lines, insert Pay, Grade, and Wef (stands for with-effect-from) Fields.

    When completed, it will look like the following image:

    We need two more pieces of data for the Reference Sequence Number and Letter Date.

  16. Position the insertion point at the end of the existing reference number, immediately after the dash character (Ref: ABC/HRD/2020/1234-).

  17. Select Page Number from the Insert Menu and select Current Position from the displayed list.

  18. Position the insertion point after the word Date:.

  19. Click on the Date & Time option, under the Insert Menu, and select one of the date format options displayed.

  20. Press Ctrl+S Keys to save the Word Document with the changes.

Merge-Printing the Letter.

Now, we are ready to merge-print the Document for each selected employee on the Employees2 Table.

  1. Click the Preview Results button, with the Zoom Glass image, under the Mailings Menu. 
  2. If it is still on Field-Code display, then press ALT+F9 Keys to fill in the first Employee data wherever we have inserted the Merge-Fields on the Document.
  3. Now, you are viewing the sample Document you will get when you merge-print the Document, on the Printer, one Document per employee.
  4. Now, click the Finish & Merge button and select Edit Individual Document...,  and select All.

All the Documents are merged with Employee information, and you are allowed to edit the pages if needed.  Can insert spaces between lines or the inserted information in Bold letters. 

Once you are finished editing, select Print from the Office Button, then Preview or Print the Document on Paper.

If you have selected Send Email Message at Step 4 above, then you can send the Document as an Email Message.

  1. MS-Access and E-Mail
  2. Invoke Word Mail Merge from Access2007
  3. Automated Email Alerts


Share:

Auto-Numbers in Query Column Version-2

Auto-Numbers in Query Column Version 2.

In January 2010, I published an article, “Function: QrySeq() – Auto-Numbering in Query Column,” on this website. Over the years, it has been well received by readers. While reviewing the article again, I thought the Function could be rewritten with less code and improved performance than a variant Array.

When the QrySeq() function is called for a record in the query, the program searches the Array of Unique Keys for the key value passed from the record as a Parameter. Once it finds a matching key, it retrieves the corresponding sequence number from the Array element and returns it to the calling record.

If the query contains a large number of records, this process can take considerable time because the program begins the search from the start of the Array each time it looks for a key value.

The New Version is Named: QryAutoNum()

Using a Collection Object instead of an Array.

You can find a detailed discussion of the Collection Object on the MS Access and Collection Object Basics Page.

Here, we will have a brief introduction to the Collection Object, including what it is and how it is used in VBA. The Collection Object is a versatile Object that can generally hold any type of value, including numeric or string values, Class Module Objects, or a collection of other Objects. The Collection Object is instantiated in VBA programs as follows:

'declare a Collection Object. Dim ABC as Collection 'create an instance of Collection Object in Memory Set ABC = New Collection 'We can Add built-in data types: Numeric, Strings etc ‘or Objects like Class Module Objects, ‘or other Collection Object as Items to the Collection Object.

'Use the Add method to add a Collection Item to the Object. ABC.Add 25 ABC.Add "ms-accesstips" 'When Collection Object Items added this way, ‘it can be retrieved only in the added order. For j = 1 to ABC.Count 'gets the count of Items Debug.Print ABC(J)’ retrieve in Item index Order. Next 'When ADDed an Item with a String Key 'we can use the Key value to retrieve the Items Randomly. 'But, usage of Key is optional. ABC.Add 25, "1" ABC.Add "ms-Accesstips", "2" x = "2" Debug.Print ABC(x) Result: ms-accesstips

We will use the Collection Object to store the Query Auto-numbers, with the corresponding Unique Key Values assigned as the Collection Object Keys. With this approach, we can retrieve the Auto-numbers directly, eliminating the need to work with Arrays and their more complicated data storage and retrieval steps.

The QryAutoNum() Function Code.

Option Compare Database
Option Explicit

Dim C As Collection

Public Function QryAutoNum(ByVal KeyValue As Variant, ByVal KeyfldName As String, ByVal QryName As String) As Long
'-------------------------------------------------------------------
'Purpose: Create Sequence Numbers in Query Column Ver.-2
'Author : a.p.r. pillai
'Date : Dec. 2019
'All Rights Reserved by www.msaccesstips.com
'-------------------------------------------------------------------
'Parameter values
'-------------------------------------------------------------------
'1 : Column Value - must be UNIQUE Numeric/String Type Values from Query Column
'2 : Column Name  - the Field Name in Quotes from where Unique Values taken
'3 : Query Name   - Name of the Query this Function is Called from
'-------------------------------------------------------------------
'Limitations - Function must be called with Unique Field Values
'            - as First Parameter
'            - Need to Save the Query, if changes made, before opening
'            - in normal View.
'-------------------------------------------------------------------
Static K As Long, Y As Long, fld As String
On Error GoTo QryAutoNum_Err

Y = DCount("*", QryName) ' get count of records for control purpose

'If KeyfldName Param is different from saved name in variable: fld
'or Value in K more than count of records in Variable: Y
'then it assumes that the QryAutoNum() is called from a different Query
'or a repeat run of the same Query. In either case the Control Variable
'and Collection Object needs re-initializing.
If KeyfldName <> fld Or K > Y Then
'initialize Control Variable
'and Collection Object
    K = 0
    Set C = Nothing
    'save incoming KeyfldName
    fld = KeyfldName
End If

'if KeyValue parameter is Numeric Type then convert
'it to string type, Collection Object needs it's Key as String Type.
If IsNumeric(KeyValue) Then
    KeyValue = CStr(KeyValue)
End If

K = K + 1
If K = 1 Then
Dim j As Long, db As Database, rst As Recordset
Dim varKey As Variant

Set C = New Collection

Set db = CurrentDb
Set rst = db.OpenRecordset(QryName, dbOpenDynaset)

'Add recordlevel AutoNumber with Unique KeyValue
'to Collection Object, in AutoNumber, KeyValue Pair
While Not rst.BOF And Not rst.EOF
    j = j + 1 ' increment Auto Number
    
    'Get key value from record
    varKey = rst.Fields(KeyfldName).Value
    
    'if numeric key convert it to string
    If IsNumeric(varKey) Then
      varKey = CStr(varKey)
    End If
    
    'Add AutoNumber, KeyValue pair to Collection Object
    C.Add j, varKey
    
    rst.MoveNext
Wend
    rst.Close
    Set rst = Nothing
    Set db = Nothing

'Retrieve AutoNumber from Collection Object
'using the KeyValue.  Works like Primary Key of Table
    QryAutoNum = C(KeyValue)
Else
    QryAutoNum = C(KeyValue)
End If

If K = Y Then 'All record level AutoNumbers are Returned
    K = K + 1 ' increment control variable
End If

QryAutoNum_Exit:
Exit Function

QryAutoNum_Err:
MsgBox Err & " : " & Err.Description, , "QryAutoNum"
Resume QryAutoNum_Exit

End Function

Sample Source Query SQL.

With the Northwind Products Table.

SELECT Products.ID, 
Products.Category, 
Mid([Product Name],18) AS PName, 
Sum(Products.[Standard Cost]) AS StandardCost, 
QryAutoNum([ID],"ID",
"Product_AutoNumQ") AS QrySeq
FROM Products
GROUP BY Products.ID, Products.Category, Mid([Product Name],18)
ORDER BY Products.Category, Mid([Product Name],18);

Review of VBA Code Line-By-Line.

In the Global Area of the Module, we have declared a Collection Object, the Object Variable C.

The QryAutoNum() Function declaration is the same as our earlier QrySeq() with three parameters.

  1. Unique Key-Value, either Numeric or String, as the first Parameter.
  2. The Key-Value Field’s Name in String Format.
  3. The Query Name in String Format.

The returned AutoNumber is in a Long Integer format.

Three Static Variables,  K and Y, are declared as Long Integers, and fld was declared as a String Variable.

All three Variables control the Code execution Paths, and determine when to initialize Collection objects and control variables.

The DCount() Function takes a count of records in the Query in Variable Y.

If the KeyFldName differs from the previously saved field name in the fld variable, the function assumes that the call originates from a new Query Record. If the field name is the same, but the value of the variable K is greater than Y, the function assumes that the earlier Query is calling QryAutoNum() again as part of a repeated run. In either case, the control variable K is reset to zero, and the Collection Object containing the existing Items is cleared from memory. The new Key field name from the KeyFldName variable is then saved in the fld variable for subsequent validation.

Next, if the KeyValue parameter is numeric, it is converted to String format using the statement KeyValue = CStr(KeyValue). The Item Key of the Collection Object must be in String format.

The variable K is then incremented by one. When K = 1, the function assumes that this is the first call to the function, originating from the first record of the Query. In this case, the main processing of the function begins.

The local temporary Variables are declared here, and their values are not preserved between calls of this function from different records of the query.

The Collection Object declared in the Standard Module’s  Global area is instantiated in memory with the statement Set C = New Collection.

The Query recordset is opened to read records. The local variable J will create Auto-numbers and add them to the Collection Object for each record.  The Unique Key-Value, read from the recordset into variable varKey, is added to the Collection Object as its Key Value.

If the varKey variable value is Numeric Type, then it is converted to String format.

The Auto-Number Value in Variable J and the string value in variable varKey are added to the Collection Object in the following statement, as its Item value, Key pairs:

C.Add J, varKey

This process is repeated for all the records in the Query.  The Auto-Numbers are generated for all records and added to the Collection Object.  All this work is done during the first call of the function from the first record of the query.

Did you notice that we are reading the Unique Key value of each record directly from the record set within the While . . . Wend Loop to add them to the Collection Object?  After adding the Auto-Numbers for all records, the record set and Database Objects are closed.

Remember, we are still on the first call of the function from the first record of the query, and the first parameter variable KeyValue still holds the first record Key Value.

The next statement QryAutoNum = C(KeyValue) retrieves the Collection Object’s first Item Auto-Number Value 1, using the Unique Key Value in parameter variable KeyValue, and returns it to the function calling record. This will happen only once because the variable K will be greater than one on subsequent calls of this function.

Function calls from the second record onward take the Else path of the If K = 1 Then statement. They retrieve the AutoNumber from the Collection Object using the KeyValue passed as a parameter and return it to the corresponding record in the Query.

This process is very fast because the required Item can be retrieved directly using the Collection Object Key, rather than searching through the Array from the beginning each time to locate the required Key.

When the Auto-number values for all records have been returned, the value of the control variable K equals Y. The record count of the Query was obtained and stored in the variable Y at the beginning of the program. At this point, K is incremented by 1, making its value greater than Y. Because K and Y are Static Variables, their values are retained in memory after the last record call has completed. If the same Query is run a second time, these variable values can be tested to determine whether the variables need to be reset and the existing Collection Object cleared from memory, allowing the entire process to start afresh.

If the QryAutoNum() function is called from the same Query again, the Static Variables and Collection Object are cleared from memory, preparing for a fresh run of the Function for the same Query or for a different Query.

The sample Report image, generated using the above Query, is shown below for reference. 

You can use the Query as the source for a Report or Form. 

A sample demo database is attached. 


  1. Auto-Numbering in Query Column
  2. Product Group Sequence with Auto-Numbers.
  3. Preparing Rank List.
  4. Auto-Number with Date and Sequence Number.
  5. Auto-Number with Date and Sequence Number-2.
Share:

Diminishing Balance Calc in Query

Diminishing Balance Calc in Query.

This is an offshoot of the earlier Function Running-Sum in Query Column.  With a few changes to the earlier Function RunningSum(), we can easily calculate the loan balance-to-pay amount after deducting the monthly amount paid at each record level.

The loan amount is payable in monthly installments.   Our simple task is to show the diminishing balance of the loan amount against each record-level installment amount in a separate Column of the Query.  The last record will have the remaining balance amount for payment.

Let us pretend that the Loan Repayable Total Amount is 1000.

Sample Query Recordset.

The sample installment payment detail records are taken from the earlier Post: Running-Sum in Query Column, as given below.

The Query SQL that calls the DiminishingBal() Function.

The SELECT Query SQL that calls the DiminishingBal() Function, in a separate Column of the Query.

SELECT Table_Units.ID, Table_Units.Units, DiminishingBal([ID],"ID","Units","DiminishingQ1") AS DiminishingBalance
FROM Table_Units;

The Query Recordset Image, with the result in the last column,  is given below:

We are using the same Query recordset as the source for the earlier RunningSum() Function here for demonstration purposes.  The Recordset should have a Unique value (Numeric or String) field and be used as the first parameter to the Function.

The Total Repayable Loan Amount is kept in a separate Table.

The Total Amount to be repaid to the Bank (1000) is kept in a separate Table with the following structure:

The DiminishingBal() Function VBA Code.

The VBA Code of the DiminishingBal() Function is given below:

Option Compare Database
Option Explicit

'Declare a Generic Object
Dim D As Object

Public Function DiminishingBal(ByVal IKey As Variant, ByVal KeyFldName As String, ByVal SumFldName As String, ByVal QryName As String) As Double
'-----------------------------------------------------------
'Function: DiminishingBal()
'Purpose : Calculate Diminishing Balance in a separate Column
'The Query can be used as source for other Processing needs,
'for Form View or Report
'-----------------------------------------------------------
'Author  : a.p.r. pillai
'Date    : December 2019
'Rights  : All Rights Reserved by www.msaccesstips.com
'-----------------------------------------------------------
'Parameter List, in the Order of it's placement
'1. Key Value Data Field
'2. Key-Field Name in String Format
'3. Field-Name for Calcuating Running Sum in String Format
'4  Query-Name in String Format
'-----------------------------------------------------------
'Remarks: The Key-Value Field should have Unique Numeric or
'String Values.
'-----------------------------------------------------------
Static K As Long, X As Double, fld As String, y As Long
Dim p As Variant

On Error GoTo DiminishingBal_Err

y = DCount("*", QryName)
'If the Function is not called by the same Query
'then initialize Dictionary Object and Variables
If SumFldName <> fld Or K > y Then
   fld = SumFldName
   Set D = Nothing
   K = 0
   X = 0
End If


K = K + 1
If K = 1 Then 'The major process of the function starts here
    Dim DB As Database, rst As Recordset
    
    'Create and instantiate the Dictionary Object
    Set D = CreateObject("Scripting.Dictionary")
    
    'Get Loan Repayable Amount
    X = DLookup("[LoanAmt]", "tblRepay", "[id] = 1")
    
    'Open the EMI Recordset
    Set DB = CurrentDb
    Set rst = DB.OpenRecordset(QryName, dbOpenDynaset)
    'Calculate cumulative record-level summary and
    'add the value into Dictionary Object as it's Item
    While Not rst.EOF And Not rst.BOF
    'read the record summary field value and add it to total
         X = X - rst.Fields(SumFldName).Value
    'read current record key field value
         p = rst.Fields(KeyFldName).Value
    'add the total value to dictionay object
    'as Key, Item pair
         D.Add p, X
    ' repeat this process for all records
         rst.MoveNext
    Wend
    
    'close recordset and remove the database objects
    rst.Close
    Set rst = Nothing
    Set DB = Nothing
    
    'Retrieve the first item from Dictionary,
    'using the first Key passed as parameter,
    'and return to the function calling record in the Query
    
   DiminishingBal = D(IKey)
Else
   'Subsequent calls with the record Key passed as parameter
   'will retrieve other record values from Dictionary and
   'returns to their corresponding records in the Query.
   
   DiminishingBal = D(IKey)
End If

'A control forcing to initialize the static variables
'when the program is rerun for the same query.
   If K = y Then
      K = K + 1
   End If

DiminishingBal_Exit:
Exit Function

DiminishingBal_Err:
MsgBox Err & ":" & Err.Description, vbOKOnly, "DiminishingBal()"
Resume DiminishingBal_Exit
End Function

How the Function Works.

In the Global declaration area of the VBA Module, Variable D is declared as an Object.

The DiminishingBal() Function needs four parameters:

  1. A Unique Value Field (Numeric or String Values) is the first parameter.  The parameter is declared as a Variant data Type.
  2. The Unique Value’s Field Name is the second parameter in String format.
  3. The Loan Installment Value Field Name.
  4. The Query Name is the fourth Parameter.
  5. Four Static Variables K, X, fld, and y are declared.  They must be Static Variables to retain their values between repeated calls of the Function, from each record of the Query.  The Variable p is declared as a Variant Type normal variable to hold the Key-Value (either Numeric or String) of each record.

    The DCount() Function takes the Query record count in Variable y. The Value in this Variable is used as a control to check when to reset the Static Variable Values to their initial Values and to remove the Dictionary Object from memory.  This control is necessary if the same Query is run more than once, consecutively.

    1. If the control variable K value is more than the Query record count variable y, then the Static variables are reset to their initial values and the Dictionary Object is deleted from memory.
    2. Or, if the installment value Field Name is different from the field name saved in Variable fld during the last call of the function,  then it assumes that the Function is called from a different Query Column and resets the Static Variable Values. The Dictionary object is deleted from memory.

    Next, Variable K is incremented by 1.  When K=1, the main action of the Function starts.  The Database and Recordset Objects are declared in the DB and the rst variables, respectively.

    In the next executable statement, Set D = CreateObject("Scripting.Dictionary") creates the Dictionary Object with the CreateObject() method and assigns it to the Object variable D, which was declared in the Global Area of the Module.

    There are other ways to declare and use this Object by adding the Microsoft Scripting Runtime File to the Microsoft Access Reference Library List.  After that, you can create an instance of the Dictionary Object in the following way:

    Dim D As Dictionary
    Set D = New Dictionary
    

    If you are new to the Dictionary Object and its usage, visit the Post: Dictionary Object Basics.  There are five Posts on this Topic, and you can find the links at the end of this Page.

    Next, we need the value of the repayable total Loan Amount and retrieve it from its Table tblRepay with the dlookup() function in the statement: X = DLookup("[LoanAmt]", "tblRepay", "[id] = 1").  There is only one record in the Table with ID 1, so omit the criteria part.

    The Query Recordset is open to read records one by one. The first record’s amount paid to the bank is deducted from the Loan Amount (1000) in Variable X.  The Unique Key value of the record is retrieved and saved in Variable p in the next statement.

    The balance loan amount, calculated after deducting the repaid Amount, is added to the Dictionary Object with the Dictionary Object’s  Add Method as its Item Value, with the Unique Key field value in the variable p as Dictionary-Key in the statement: D.Add p, X. The Dictionary’s Add method always adds its Item value in Key, Item pairs.

    Note: If the Key-Value is not unique, the Add method fails with Errors.

    With the rst.MoveNext statement moves to the next record and adds the result value to the Dictionary Object.

    This way, the individual record value is deducted from the remaining loan balance amount at that level and added to the Dictionary Object as its Item.

    Note: Here, you may ask why the Dictionary Object is chosen to hold all the calculated values rather than in an Array.  Yes, it can be done, but that method needs more statements to store and retrieve the values in a two-dimensional array. It will become more complicated when the Query Record’s Unique Key Value is in String form.  The Dictionary Object allows you to retrieve the value in either sequential or random order based on its Key.  Here, the Random method works fine with the Key-Value Type in the Numeric or String form.

    When all the record processing is complete, the record set and Database Objects are closed.

    What you have to keep in mind at this point is that the value in variable K is still 1, and the first Parameter IKey retains the unique ID value.  At the first record-level function call, DiminishingBal() calculated all record-level balance loan amounts and added them as Dictionary Object Items. The function parameter IKey still holds the first record’s Unique ID value. That is why we have used a separate variable p for the individual record key during the processing of all records.

    So, the entire record-level processing is done during the first call of the function, initiated from the first Query record, and all record-level result values are held in temporary storage in the Dictionary Object.

    The next statement DiminishingBal = D(IKey) retrieves the first value, adds it to the Dictionary using the unique parameter value IKey,  and returns the value to the calling first record of the Query.

    The next call from the second record of the Query increments the variable K by 1 (now K=2), and the program takes the ELSE path of the IF...Then the statement retrieves the second Item value from the Dictionary Object, using the IKey parameter, and returns it to the corresponding Query record.

    The rest of the DiminishingBal() function call, from the remaining records, will route the program control only through the ELSE path because the value in Variable K is greater than one, retrieves the values from the Dictionary Item, and returns it to the calling record.

    The Next If . . . Then statement checks whether the value in variable K = y.  Variable y holds the total record count of the Query.  If it is found to be True, then it assumes that the last call of the DiminishingBal() function has arrived.  At this point, the K variable is made greater than the control variable y.

    This is necessary to initialize the Static Variables during the Query rerun. If any change is made to the Source Data before the rerun, it will not be reflected in the balance amount calculated earlier, because it will keep taking the ELSE route in the If ... Then statement and retrieve the old value from the Dictionary Object.

    The Demo Database, with all the necessary Objects and the Code Module, is attached for your convenience to download and try it out straight away.


    Dictionary Object Links.

    1. Dictionary Objects Basics
    2. Dictionary Object Basics- 2
    3. Sorting Dictionary Object Keys and Items
    4. Display Records from Dictionary
    5. Add Class Objects as Dictionary Items
    6. Update Class Object Dictionary Item
Share:

Opening Access Objects from Desktop

Opening Access Objects from the Desktop.

  1. Set the Form Name in the Display Form Option of the current database in Access Options.

    BIG DEAL! This is the first trick any novice learns when he/she starts learning Microsoft Access.

  2. Create an AutoExec macro with the FormOpen action and the required Form Name in the Property.
  3. The above method opens the form when the database is launched.

Opening a Form Directly, without any Changes to the Database.

We would like to launch a specific Form tomorrow to continue updating data in that form, without making any changes in the database.

If you would like to print a particular Report, first thing in the morning without fail, then here is a simple trick.

Note: Your Database's Navigation Pane must be accessible.

  1. Open the Database.

  2. Click the Restore Window Control Button to reduce the Application Window size, so that the empty area of the Desktop is visible.

  3. Click and hold the Mouse Button on the Form Name in the Navigation Pane, then drag the form to the desktop and drop it there.

  4. Close the Database.

  5. Double-Click on the Desktop-Shortcut. The Form will open when the Database is open.

    You can open the following Objects directly with Desktop-Shortcuts:

Try it out yourself.

  1. MS-Access Class Module and VBA
  2. MS-Access and Collection Object Basics
  3. Dictionary Objects Basics
  4. Withevents and All Form Control Types
Share:
Listen to this article
Ready to read.

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