Introduction.
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 article is a continuation of an earlier tutorial and 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 an arrowhead icon pointing left for the normal view and change to an arrowhead pointing right when selected.
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 one 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, etc. There are plenty of free icon collections available 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) as well as 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—say 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 into 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 into the ImageList control, then experiment with them in the TreeView control by adjusting the last two parameters in the Nodes.Add() method.
Preparing for the Trial Run
-
Open the
ProjectMenu.accdb
database. -
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.
-
-
Open
frmMenu
in Design View. -
On the Design tab, in the Controls group, click ActiveX Controls.
-
In the list, locate Microsoft ImageList Control.
-
Click OK to insert it onto the form.
-
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:
Display its Property Sheet and change the Name Property value to ImageList0.
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.
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 here takes effect on all Images we add to the ImageList Control.
Click the Apply Command Button and then the OK button to close the Property Sheet.
First, we must add the required images to the ImageList Control before we can use them in the Tree View Control.
Image Loading Approaches
There are two ways to add images to the ImageList control:
-
The Easy Way – Add images directly through the control’s property sheet, without using VBA.
-
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, they can be assigned to nodes at run time.
Syntax of the Add()
Method
-
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 and 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 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 Tree View Nodes.
The TreeView Nodes' Add() Method and Image Parameters.
The Tree View Object Add() Method’s last two parameters are for the Node Images. Let us look at 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()
Methods 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 FormLoad() 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 normal and click views of the images.
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 the easy method for adding images — and I’ll share my own sample images with you.
Hi APR, thanks for the post. I downloaded the sample but my code is erroring out on the LoadPicture lines, as the pictures were not included in the zip file. Any chance you could include the pics in the zip with the sample? Thanks!
ReplyDeleteThe ImagesTreeView.zip File is added to the Page. Please download and Unzip the contents into the same TreeView Database Folder.
ReplyDeleteMr Pillai, thank you so much. I was trying to add various pictures to my image control list from all over the internet, as well as Win 10, for open folder & closed folder. Yours worked! Much appreciated for this and your other instruction pages. The Common controls are very different from the list boxes and combo boxes I have been working with the last 25+ years, and your sample pages are very helpful. Best regards,
ReplyDelete