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

Assigning Images to TreeView Nodes

Assigning Image Icons to TreeView Nodes.

Last week, we created the Access Project Menu using a TreeView Control, and I trust you were able to build it in your own version of Microsoft Access and run it successfully.

For your reference, there is a Demo Database—originally created in Access 2007—attached to the article linked below:

Creating an Access Menu with a Tree View Control.

You can download this database, add the new VBA code from today’s topic, and test it in the same environment.

This is the second part of an earlier tutorial that uses the same Demo Access Menu Project. We will focus on assigning images to the TreeView nodes.

MS Office / Windows Version Issues with the TreeView Control

If you encounter problems running the Demo Database in your version of Microsoft Access, you may find the following link helpful. It contains corrective steps for common compatibility issues:

SOLVED – MSCOMCTL.OCX Download, Register in 64-bit Windows


Sample Demo Image

When we complete our Access Project Menu, the TreeView nodes will appear with images, as shown in the sample image below:

Optionally, you can assign two images to each TreeView node—one for the normal state and another for when the node is selected (clicked).

For example:

  • Root-level Nodes can display a Closed Folder icon in the normal view and switch to an Open Folder icon when clicked.

  • Child Nodes might use a left-pointing arrowhead icon in the normal view and change to a right-pointing arrowhead when the node is in the selected mode.

If you prefer, you can use the same image for both the normal and selected states. In that case, the icon will remain unchanged when a node is clicked. However, note that if you provide only one of the two parameters—say, the normal view image—and leave the second blank, the node will display no image when clicked.


Ideal Image Sizes for TreeView Nodes

You can use almost any standard image format—BMP, JPG, JPEG, ICO, TIFF—there are plenty of free icon collections online.

The ideal image size for a crisp, balanced display is 16 × 16 pixels. The ImageList control provides preset size options (16×16, 32×32, 48×48 pixels) and a custom size setting.

  • 16×16 pixels – Best for compact, clean menus.

  • 32×32 or 48×48 pixels – Larger, more detailed icons, but they take up more space on the TreeView display.


Example – Different Image Sizes in Action

The sample image below shows a 32 × 32 pixel icon applied to a TreeView node:

TreeView Control with Node Image Size 48 x 48 Pixels:

If you choose the Custom Image option, the actual size of the image you provide will be displayed exactly as it is—no automatic resizing will be applied.


Image Quality and Size Considerations

In the first sample image above, we used 16 × 16 pixels. If you upload a larger image—512 × 512 pixels—but set the option to display it at 16 × 16, the control will shrink the image. While the size will fit, the clarity will usually suffer, resulting in a blurry or distorted look.

Best practice:

  • Start with high-quality small images that already fit in a 16 × 16 pixel canvas.

  • Such images work perfectly with both the 16 × 16 preset and custom sizing, without losing clarity.


Experiment Before Finalizing

You can try out different:

  • Image formats (BMP, JPG, PNG, ICO, TIFF, etc.)

  • Pixel dimensions

  • Color depths

Use tools like MS Paint or any other image editor to create, import, or adjust your icons until they look just right.


Preparing for the Next Step

Before we continue, create four or more small icons and save them in the same folder as your database. Upload these images to the ImageList control, then do experiments with them in the TreeView control by adjusting the last two parameters in the Nodes.Add() method. 

Preparing for the Trial Run

  1. Open the ProjectMenu.accdb database.

  2. Make a backup copy of the form:

    • In the Navigation Pane, right-click frmMenu.

    • Select Copy → then Paste.

    • Name the copy as frmMenu2. Keep this as a safe backup before making changes.

  3. Open frmMenu in Design View.

  4. On the Design tab, in the Controls group, click ActiveX Controls.

  5. In the list, locate Microsoft ImageList Control.

  6. Click OK to insert it onto the form.

  7. Drag and place the ImageList control anywhere in an empty area of the form (its position won’t affect functionality).

    Form with ImageList Control highlighted in Design View is given below for reference:

  8. Display its Property Sheet and change the Name Property value to ImageList0.

  9. Right-click on the ImageList Control and highlight the ImageListCtrl Object Option in the displayed menu, and select Properties to display the Control’s Image settings Property Sheet.

  10. Select the 16 x 16 image size Radio Button on the General Tab, indicating that we need the smallest of the three image sizes for the Node.  The setting affects all Images we add to the ImageList Control.

  11. Click the Apply Command Button and then the OK button to close the Property Sheet.

First, add the required images to the ImageList Control before we can use them in the TreeView Control.

Image Loading Approaches

There are two ways to add images to the ImageList control:

  1. The Easy Way – Add images directly through the control’s property sheet, without using VBA.

  2. The Hard Way – Use VBA code to load images programmatically.

We will start with the hard way first, so you can see how to work with VBA when you need more flexibility—such as experimenting with different image sizes—before deciding what looks best on the TreeView nodes.

With VBA, we use the ImageList object’s Add() method to load images into the control, similar to how we added nodes to the TreeView. Once images are stored in the ImageList and assigned to the nodes at runtime.


Syntax of the Add() Method

ImageList.ListImages.Add Index, Key, Picture
  • Index – Optional. The position number where the image will be inserted in the list.

  • Key – Optional. A string identifier to refer to the image by name.

  • Picture – Required. The actual image to be added (must be provided as an Picture object).

Example usage:

ObjImgList.ListImages.Add([Index],[Key],[Picture]) As ListImage

The first two parameters of the Add() method are optional. The third parameter uses the LoadPicture() function to load images from the specified file path and add them to the ImageList. This function requires the full file path name of the image. Each image is added sequentially to the ImageList object in the order they are processed. The Index values are automatically assigned as consecutive numbers, starting from 1.

Once all images have been loaded into the ImageList, the final step is to assign the ImageList object to the TreeView control’s ImageList property. This links the two controls together so that nodes in the TreeView can use the images stored in the ImageList.

The VBA Code.

The sample VBA Code for loading images for our Menu above is given below:

Dim tvw As MSComctlLib.TreeView
Const KeyPrfx As String = "X"
Dim objimgList As MSComctlLib.ImageList

Private Sub CreateImageList()
Dim strPath As String

'TreeView Object reference set in tvw
Set tvw = Me.TreeView0.Object
'Clear the Tree View Nodes, if any.
tvw.Nodes.Clear

'ImageList Object reference set in objimglist
Set objimgList = Me.ImageList0.Object

strPath = CurrentProject.Path & "\"

With objimgList.ListImages
'Key Names are Case sensitive.
    .Add , "FolderClose", LoadPicture(strPath & "folderclose2.jpg")
    .Add , "FolderOpen", LoadPicture(strPath & "folderopen2.jpg")
    .Add , "ArrowHead", LoadPicture(strPath & "arrowhead.bmp")
    .Add , "LeftArrow", LoadPicture(strPath & "LeftArrow.bmp")
    .Add , "RightArrow", LoadPicture(strPath & "RightArrow2.bmp")
End With

With tvw
    .ImageList = objimgList
End With

End Sub

Once we are through with this procedure, it is easy to add the images to the TreeView Nodes.

The TreeView Nodes' Add() Method and Image Parameters.

The last two parameters of the TreeView Object's Add () Method are for the Node Images.  Let us examine the TreeView Object Node's Add() method Syntax one more time:

tvw.Nodes.Add([Relative],[Relationship],[Key],[Text],[Image],[SelectedImage]) As Node

The last two parameters in the Nodes.Add() Method are used to assign images to a node. The first parameter specifies the image for the node’s normal view, while the second specifies the image to display when the node is selected. Both the Image and SelectedImage values can be provided either as the ImageList index number or as the key value assigned to the image.

In our example, the CreateImageList subroutine adds five images to the ImageList control. Of the first two images, the first (FolderClose) is used for the root-level node’s normal view, and the second (FolderOpen) is displayed when the root-level node is selected.

Similarly, the last two images are assigned to the child nodes — one for their normal view and the other for when the node is clicked.

The ArrowHead image is ignored. 

The Form_Load() Event Procedure Changes.

The modified Form_Load () Event Procedure is given below:

Private Sub Form_Load()
Dim db As Database
Dim rst As Recordset
Dim nodKey As String
Dim PKey As String
Dim strText As String
Dim strSQL As String

Dim tmpNod As MSComctlLib.Node
Dim Typ As Variant

'1. Initializes TreeView Control Object
'2. Creates ImageList in ImageListObject
CreateImageList 

With tvw
    .Style = tvwTreelinesPlusMinusPictureText
    .LineStyle = tvwRootLines
    .LabelEdit = tvwManual
    .Font.Name = "Verdana"
    .Indentation = 400
End With

strSQL = "SELECT ID, Desc, PID, Type,Macro,Form,Report FROM Menu;"

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

Do While Not rst.EOF And Not rst.BOF
    If Nz(rst!PID, "") = "" Then
        nodKey = KeyPrfx & CStr(rst!ID)
        strText = rst!desc
      Set tmpNod = tvw.Nodes.Add(, , nodKey, strText, "FolderClose", "FolderOpen")
      
      'Root-Level Node Description in Bold letters
      With tmpNod
        .Bold = True
      End With
    Else
        PKey = KeyPrfx & CStr(rst!PID)
        nodKey = KeyPrfx & CStr(rst!ID)
        strText = rst!desc
        Set tmpNod = tvw.Nodes.Add(PKey, tvwChild, nodKey, strText, "LeftArrow", "RightArrow")
     
     'Check for the presense of Type Code
        If Nz(rst!Type, 0) > 0 Then
            Typ = rst!Type
            Select Case Typ
                Case 1 'save type Code & Form Name in Node Tag Property
                    tmpNod.Tag = Typ & rst!Form
                Case 2 'save type Code & Report Name in Node Tag Property
                    tmpNod.Tag = Typ & rst!Report
                Case 3 'save type Code & Macro Name in Node Tag Property
                    tmpNod.Tag = Typ & rst!Macro
            End Select
        End If
        
    End If
    rst.MoveNext
Loop
rst.Close

Set rst = Nothing
Set db = Nothing

End Sub

In the VBA code shown above, the Add() Method line for adding TreeView nodes has been highlighted. Here, the image key string parameter values are specified for both the image normal and click views.

Alternatively, you can use image index values — for example, 1 and 2 for the root-level nodes, and 4 and 5 for the child nodes.

Feel free to change these values and experiment.

A new demo database, containing all the changes and additional image-loading procedures, is attached for you to download.

Note: For your own trial runs, create four new images as explained earlier. If you save the images in a different location, remember to update their names and file paths in the VBA code accordingly.

Next, we’ll explore an easy way to add images—and I’ll share my sample images with you.

Sample Database for Download.


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

Share:

Creating Access Menu with Tree View Control

TreeView Control and Access Menu.

The Microsoft Access Project Menu, when completed with the TreeView Control, resembles the image shown below.

In the image above, the third option under the Report Group, Custom Report, is selected and highlighted. The Report Filter Parameter Form is open, overlapping the Menu Screen, ready for the user’s input.

Before we get into that, let’s briefly revisit last week’s lesson. We explored how to organize related items into a hierarchical structure using the Microsoft TreeView control, based on a sample data table.

Last week, I emphasized that related items in the TreeView control’s data do not need to appear next to each other in the table. In this session, we will take that concept further by showing how to update the Relative Keys of child nodes—regardless of the physical record's position in the table—based on their relationship to their parent node IDs.

Here is the data table we worked with and completed in last week’s exercise:

Can you add the following list of items at the end of the above table and update their ParentID field values, so that the TreeView Control display will look like the sample image given below:

New records for the Table item record-related field:

  1. Text Field.
  2. Number Field.
  3. Date/Time Field.
  4. Hyperlink Field.

Form-related Controls:

  1. Text Box.
  2. Command Buttons.
  3. Combo Box.
  4. List Box.

Report-related Controls:

  1. Text Box.
  2. Label.
  3. Graph Chart.

Assign ParentID Values to these items so that the Tree View Display looks like the following Image:

Now, we will create an MS Access Project Menu and learn what it takes to create one. A simple Menu Image is given below:

A simple menu containing three main groups of options: Forms, Report Views, and Macros.

  • Forms Group

    • The first option displays the TreeView control’s menu table records.

    • The second option presents the same records in Continuous Form view.

  • Report Views Group

    • The first option generates a report of product categories from the Categories table in the NorthWind.accdb database.

    • The second option displays the Products List-Price Report.

    • The third option opens a Parameter Form to specify a minimum and maximum list price range to filter the Products List-Price Report data.

  • Macros Processes Group

    • The two options in this group run Macro1 and Macro2, respectively, each displaying a different message.

To implement this menu, we need a Menu Table with the option records above, and some additional fields beyond the standard TreeView fields—Unique ID, Description, and ParentID. The image below shows the structure of this menu table:

Create a Table with the above structure, add the menu records above, and save it as Menu.  The ID field is an AutoNumber, the PID and Type fields are numeric, while the remaining fields are text.

We are already familiar with the first three fields: Unique ID, Description, and ParentID. The ParentID Field Name is abbreviated as PID for convenience.

We now need four additional fields in the Menu Table:

  1. Type – Stores the Access object type code.

  2. Form – Stores form names (object type code: 1).

  3. Report – Stores report names (object type code: 2).

  4. Macro – Stores macro names (object type code: 3).

Note: While all object names could be stored in a single column, we are using separate fields for clarity. If you decide to use a single column, remember to adjust the VBA code wherever the field names are referenced.

The Type field helps us determine which action to take when a user clicks on an option:

  • If the type is 1, open the form using DoCmd.OpenForm.

  • If the type is 2, open the report using DoCmd.OpenReport.

  • If the type is 3, run the macro using DoCmd.RunMacro.

When we start adding nodes to the TreeView control, we will store both the Type Code and the Object Name for each child node.

Additional Required Tables and Objects.

We will also need two additional data tables—Categories and Products—from the NorthWind sample database.

To save time, a demo database containing the required objects and programs is provided at the end of this page for download and learning.

Creating the Forms and Reports

  1. Create two forms based on the Menu Table:

    • Data Entry (single form view)

    • Data View (continuous form view)

  2. Create two reports:

    • Categories – Based on the Categories table.

    • Products Listing – Based on the Products table.

      • Add a long label below the main heading and set its Name property to Range.

  3. Create a small form for filtering products:

    • Add two unbound text boxes.

    • Set their Name property values to Min and Max.

    • Design it as shown in the sample layout below.

Add two Command Buttons as shown above.  Change the Caption Property Value of the first Button to Open Report and the Name Property Value to cmdReport.

Change the Second Command Button’s Caption to Cancel and the Name Property value to cmdCancel.

Display the Form's Code Module.  Copy and Paste the following Code into the Form Module and save the Form:

Private Sub cmdOpen_Click()
Dim mn, mx, fltr As String
mn = Nz(Me![Min], 0)
mx = Nz(Me![Max], 9999)
If (mn + mx) > 0 Then
    fltr = "[List Price] > " & mn & " And " & "[List Price] <= " & mx
    DoCmd.OpenReport "Products Listing", acViewReport, , fltr, , fltr
Else
    DoCmd.OpenReport "Products Listing", acViewReport
End If

End Sub

Private Sub cmdCancel_Click()
DoCmd.Close
End Sub

When the user specifies a value range by entering the Minimum and Maximum list prices in their respective text boxes, a report filter criterion string.

This filter string is:

  • Passed to the Products Listing report as a filter parameter in the DoCmd.OpenReport command.

  • Also sent as the OpenArgs (open argument) parameter.

The filter parameter limits the report data to records that fall within the specified Min and Max price range.

The OpenArgs value updates the Range label’s caption when the report opens, so the user can see the filter range they applied.

Copy and paste the following VBA code into the Products Listing report’s code module:

Private Sub Report_Open(Cancel As Integer)
    DoCmd.Close acForm, "Parameter"
    Me.Range.Caption = Nz(Me.OpenArgs, "")
End Sub
  1. Create a new form named frmMenu, and add the Microsoft TreeView Control from the ActiveX Controls List as shown in the Design View below:

  2. Change the Tree View control’s name to TreeView0 in the standard Property Sheet.

    Add a Command Button below the Tree View control.

    • Set its Name property to cmdExit.

    • Set its Caption property to Exit.

    Right-click the TreeView control, choose TreeCtrl_Object, and select Properties to open its Property Sheet.

    Update the following property values:

    • Style = 7 (tvwTreeLinesPlusMinusPictureText)

    • Line Style= 1 ( tvwRootLines)

    • LabelEdit = 1 (tvwManual)

    Last week, we already updated the first two property values.

    By default, the LabelEdit property is set to 0 – tvwAutomatic. In that mode, clicking a node twice (not double-clicking) puts the node text into edit mode, allowing you to change it. However, this does not update the underlying data source field.

    Changing the value to 1 – tvwManual disables this automatic edit mode, preventing accidental changes to node text.

    You can also make this change programmatically by adding the following lines to the Form_Load() event procedure:

With Me.TreeView0.Object
    .Style = tvwTreelinesPlusMinusPictureText
    .LineStyle = tvwRootLines	
    .LabelEdit = tvwManual
End With

Last week, we used the Form_Load() event procedure to read the Tree View node values and create both the root-level and child nodes. We will use the same procedure here, with a few additional lines of code.

In addition to that, we need to handle the Node_Click() event to determine which option the user has selected.

Copy and paste the following VBA code into the form’s module, then save the form:

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 nodKey As String
Dim PKey As String
Dim strText As String
Dim strSQL As String

Dim tmpNod As MSComctlLib.Node
Dim Typ As Variant

Set tv = Me.TreeView0.Object
tv.Nodes.Clear


‘Change the TreeView Control Properties
With tv
    .Style = tvwTreelinesPlusMinusPictureText
    .LineStyle = tvwRootLines
    .LabelEdit = tvwManual
    .Font.Name = "Verdana"
End with

    strSQL = "SELECT ID, Desc, PID, Type,Macro,Form,Report FROM Menu;"

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

Do While Not rst.EOF And Not rst.BOF
    If Nz(rst!PID, "") = "" Then
        nodKey = KeyPrfx &  CStr(rst!ID)
        strText = rst!Desc
      Set tmpNod = tv.Nodes.Add(, , nodKey, strText)
      
      'Root-Level Node Description in Bold letters
      With tmpNod
        .Bold = True
      End With
    Else
        PKey = KeyPrfx & CStr(rst!PID)
        nodKey = KeyPrfx & CStr(rst!ID)
        strText = rst!Desc
        Set tmpNod = tv.Nodes.Add(PKey, tvwChild, nodKey, strText)
     
     'Check for the presense of Type Code
        If Nz(rst!Type, 0) > 0 Then
            Typ = rst!Type
            Select Case Typ
                Case 1 'save type Code & Form Name in Node Tag Property
                    tmpNod.Tag = Typ & rst!Form
                Case 2 'save type Code & Report Name in Node Tag Property
                    tmpNod.Tag = Typ & rst!Report
                Case 3 'save type Code & Macro Name in Node Tag Property
                    tmpNod.Tag = Typ & rst!Macro
            End Select
      End If
        
    End If
    rst.MoveNext
Loop
rst.Close

Set rst = Nothing
Set db = Nothing

End Sub

Private Sub cmdExit_Click()
If MsgBox("Close Menu Form? ", vbYesNo, "cmdExit_Click()") = vbYes Then
    DoCmd.Close
End If
End Sub

Private Sub TreeView0_NodeClick(ByVal Node As Object)
Dim varTag, typeid As Integer
Dim objName As String, nodOn as MSComctlLib.Node

If Node.Expanded = False Then
    Node.Expanded = True
Else
    Node.Expanded = False
End If


‘Reset the earlier highlight to normal
For Each nodOn In tv.Nodes
	nodOn.BackColor = vbWhite
    nodOn.ForeColor = vbBlack
    
    ‘changes BackColor to light Blue and ForeColor White
    tv.Nodes.Item(Node.Key).BackColor = RGB(0, 143, 255)
    tv.Nodes.Item(Node.Key).ForeColor = vbWhite
    
    ‘—Highlight code ends-
    varTag = Nz(Node.Tag, "")
    
If Len(varTag) > 0 Then
    typeid = Choice(varTag)
    objName = One(varTag, 2)
End If

Select Case typeid
    Case 1
        DoCmd.OpenForm objName, acNormal
    Case 2
        DoCmd.OpenReport objName, acViewPreview
    Case 3
        DoCmd.RunMacro objName
End Select
End Sub

The TreeView object is declared in the module's global declaration area. A constant variable, KeyPrfx, is defined with the value "X".

The Form_Load() event procedure from last week’s article has been updated with additional code. I have added comments to the new segments to indicate their purpose, and I will explain them in detail.

The procedure begins by declaring the Database, Recordset, and four String variables. The next two lines declare a temporary Node object (tmpNod) and a Variant variable named Typ.

The TreeView object tv is then set to reference the TreeView0 control on the form. Any existing nodes in TreeView0 are cleared using: tv.nodes.clear statement

tv.nodes.clear

This ensures we start with a clean slate before reloading all nodes.

Finally, we have implemented code to modify the TreeView control’s properties programmatically. 

With tv
    .Style = tvwTreelinesPlusMinusPictureText
    .LineStyle = tvwRootLines
    .LabelEdit = tvwManual
    .Font.Name = "Verdana"
End With

The TreeView font is set to Verdana for a cleaner look. c

The SQL string has been updated to include the new fields—Type, Form, Report, and Macro—from the Menu table.

When the procedure runs, the first record in the Menu table is searched for a PID value.

  • If the PID field is empty, it is treated as a root-level node. The record is added to the Tree View as a root node, and its reference is stored in the tmpNod object. To visually distinguish root nodes from child nodes, the Bold property is set to True.

  • If the PID field contains a value, the record is treated as a child node. In this case, the program checks the Type Field Value. If the Value is 1, 2, or 3, the corresponding object name is taken from the Form, Report, or Macro field, prefixed with its Type code (e.g., "1Data Entry", "2Categories", "3MyMacro"), and stored in the node’s Tag property.

The Tag property—available in most Access controls such as text boxes, labels, and command buttons—allows us to store hidden, custom data with each control. In this case, it serves as a convenient way to store both the Type code and object name for later use.

The cmdExit_Click() procedure prompts the user for confirmation and closes the menu form if the response is affirmative.

When a user clicks a child node, the program retrieves the value stored in the node’s Tag property. Based on the Type code, it determines whether to open a form, run a report, or execute a macro. This logic is implemented in the TreeView0_NodeClick() event procedure.

Private Sub TreeView0_NodeClick(ByVal Node As Object)
Dim varTag, typeid As Integer
Dim objName As String, nodOn as MSComctlLib.Node

If Node.Expanded = False Then
    Node.Expanded = True
Else
    Node.Expanded = False
End If

‘Reset the earlier lighlight to normal
For Each nodOn In tv.Nodes
  nodOn.BackColor = vbWhite 
  nodOn.ForeColor = vbBlack
Next nodOn

‘changes BackColor to light Blue and ForeColor White
    tv.Nodes.Item(Node.Key).BackColor = RGB(0, 143, 255)
    tv.Nodes.Item(Node.Key).ForeColor = vbWhite
‘—Highlight code ends-

varTag = Nz(Node.Tag, "")
If Len(varTag) > 0 Then
    typeid = Choice(varTag)
    objName = One(varTag, 2)
End If

Select Case typeid
    Case 1
        DoCmd.OpenForm objName, acNormal
    Case 2
        DoCmd.OpenReport objName, acViewPreview
    Case 3
        DoCmd.RunMacro objName
End Select
End Sub

The Click() event procedure receives a reference to the clicked node through the Node parameter. At the start of the procedure, a few declared variables are for later use.

The next section checks whether the clicked node is currently expanded or collapsed.

Normally, to expand a node and reveal its child nodes, you either click the plus (+) symbol to the left of the node or double-click the node itself. Likewise, double-clicking the node again or clicking the minus (–) symbol collapses it, hiding the child nodes.

This process is simplified with the following code segment—allowing you to expand or collapse a node with a single click instead of the usual two-step interaction.

If Node.Expanded = False Then
    Node.Expanded = True
Else
    Node.Expanded = False
End If 

The next six executable lines ensure that the Node that received the Click remains highlighted.

‘Reset the earlier Highlight to Normal
For Each nodOn In tv.Nodes
  nodOn.BackColor = vbWhite 
  nodOn.ForeColor = vbBlack
Next nodOn
‘Changes BackColor to light Blue and ForeColor White
    tv.Nodes.Item(Node.Key).BackColor = RGB(0, 143, 255)
    tv.Nodes.Item(Node.Key).ForeColor = vbWhite
‘—Highlight code ends-

Next, the varTag variable is assigned the value from the node’s Tag property. If this value is not empty, it is split into two parts:

  • The numeric portion is extracted and stored in the Typid variable.

  • The object name portion is stored in the objName variable.

Based on the value of 'Typid'The appropriate DoCmd action is executed to open a form, open a report, or run a macro.

We will also add two additional command buttons at the top of the menu:

  • One button to expand all nodes with a single click.

  • Another button to collapse all nodes with a single click.

  1. Place these two buttons in the top area of the TreeView control, as shown in the design layout below.

  2. Change the Name Property Value of the left Command Button to cmdExpand and the Caption to Expand All.

  3. Similarly, change the right-side Command Button’s Name Property to cmdCollapse and the Caption to Collapse All.
  4. Copy and paste the following VBA Code below the existing Code in the frmMenu Form Module and save the Form.
Private Sub cmdExpand_Click()
Dim Nodexp As MSComctlLib.Node

For Each Nodexp In tv.Nodes
    If Nodexp.Expanded = False Then
        Nodexp.Expanded = True
    End If
Next Nodexp
End Sub


Private Sub cmdCollapse_Click()
Dim Nodexp As MSComctlLib.Node

For Each Nodexp In tv.Nodes
    If Nodexp.Expanded = True Then
        Nodexp.Expanded = False
    End If
Next Nodexp
End Sub

At the beginning of the cmdExpand_Click() event procedure, we declare a TreeView Node object named NodExp. The For… Next Loop iterates each node, checking its expanded state. If the node is not expanded, its Expanded property is set to True.

The cmdCollapse_Click() event follows the same approach. However, instead of expanding nodes, it checks if they are currently expanded; if so, it sets their Expanded property to False.

With these two commands, you can:

  • Instantly expand the entire TreeView, making all child nodes visible.

  • Collapse all child nodes so that only the root-level nodes remain visible.

If you have followed each design step carefully, your menu should now look like the finished menu image shown at the top.

Back in 2007, I designed a similar menu for a Vehicle Service Contract System project. That version used a Tab Control with multiple pages. Each page displayed 10 or more options in the middle panel, and the user could switch pages by clicking command buttons arranged along either side of the menu. 

You can find the Menu Design with Tab Control Article at this Link:https://www.msaccesstips.com/2007/06/control-screen-menu-design.html


CLASS MODULE

  1. MS-Access Class Module and VBA
  2. MS-Access VBA Class Object and Arrays
  3. MS-Access Base Class and Derived Objects
  4. VBA-Base Class and Derived Object-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

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