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

ListView Control Tutorial-02

ListView Control Tutorial.

Continued from last week's ActiveX ListView Control Tutorial-01.

In this session, we will learn how to search for specific rows and column values in the ListView control and display the search results in a Label control on the form. This capability is particularly useful when working with large volumes of data. We will also examine several important ListView property settings.

To begin, we will see how easily columns can be rearranged in the ListView control, similar to the column arrangement available in the Access Datasheet View. To support this demonstration, additional controls—including TextBoxes, ComboBoxes, CommandButtons, and Labels—were added to the Form to facilitate search parameter selection and search results.

For this demonstration, I have made a slight modification to last week's sample data. The values in the first column are now sourced from the Employees table in the Northwind sample database. A query was created to combine the LastName and FirstName fields into a single field, aliased as Student, while the EmployeeID field is used as the Key (for example, X01, X02, and so on).

Before moving on to search operations, let us first explore how to rearrange columns in the ListView control using the drag-and-drop feature.

Note: If you have not completed the previous tutorial and would like to continue directly with this session, download the demo database from the ListView Control Tutorial-01 page. Extract the ZIP file, open the database, and you will find the demo form ready in Normal View.

Open the database containing the demo form from the previous session (or the one you created) and switch the form to Normal View.

Now, let us rearrange a column by dragging it from the middle of the list. For example, drag the Weight column and drop it in the position of the Age column. The expected result is that the Age column shifts one position to the right, making room for the Weight column.

Move the mouse pointer over the Weight column header, then press and hold the left mouse button. You will notice that when the button is depressed, the column header moves slightly downward. While holding the mouse button, drag the column to the left and drop it onto the Age column header.

At this point, you will notice that nothing happens. This is because the required property setting has not been enabled. In fact, enabling a single property is all that is required for this feature to work.

To enable it:

  1. Switch the form to Design View.

  2. Right-click on the ListView control, highlight the ListViewCtrl Object option, and select Properties.

  3. On the Properties window, you will find the option AllowColumnReorder on the right side. Put a check mark to enable it, then click Apply, and select the OK button to close the Properties window.

  4. Now, repeat the drag-and-drop steps explained earlier and observe the result. This simple setting is all that’s required to enable column reordering in the ListView control.

  5. You may be asking: What about rearranging rows?
    Unlike columns, row reordering requires additional programming using event procedures—similar to the drag-and-drop techniques we implemented earlier in the TreeView control. We will cover that part later in this tutorial series.

  6. For now, feel free to experiment by moving any column, even the first column, to any position you like.

Note: Before dropping the source column, ensure that the target column is fully covered by the highlighted frame of the incoming column. If not, the column may shift to the next position on the right instead of replacing the intended target.

Next: Searching for Information in the ListView

Now, let’s move on to learning how to quickly search for information within the ListView—especially useful when working with large volumes of data.

For this purpose, we have added a subroutine to the Tutorial-01 module. This subroutine loads the column header names into a ComboBox on the form, which is displayed with a red background for visibility. The selected column name is used to search and retrieve specific values (such as Age, Height, Weight, or Class) for a student.

New VBA Code Added to the Form’s Class Module

A new VBA procedure has been added to the Class Module of last week’s Tutorial Form.

This procedure populates the txtColCombo ComboBox with a list of column header labels (field names). These labels correspond to the data fields in the ListView, such as Age, Height, Weight, or Class.

During the search-and-find operation, one of these column values can be selected to retrieve the corresponding detail for a student, along with the student’s name.

Private Sub txtColCombo()
'Column Header List Combo
Dim lvwColHead As MSComctlLib.ColumnHeader
Dim cboName As ComboBox

Set cboName = Me.txtCol
cboName.RowSourceType = "Value List"

For Each lvwColHead In lvwList.ColumnHeaders
    If lvwColHead.Index = 1 Then
        'Nothing
    Else
        cboName.AddItem lvwColHead.Text
    End If
Next
'cboName.DefaultValue = "=txtCol.Column(0, 0)"

Set lvwColHead = Nothing
Set cboName = Nothing
End Sub

The ComboBox will not have a default value for the column header name. If a column is selected, the corresponding value for the student will be displayed in the large Label below the student’s name. If left blank, the search operation will return only the student’s name.

The search operation is flexible and fast, supporting two main methods:

  1. Search by providing text – The search text can come from any column, either as a full match or as a partial string from the left. Since each row in the ListView control has two types of object members—ListItem (first column) and ListSubItems (remaining columns)—the search operation treats these separately.

  2. Search options via an option group – Next to the search-text input TextBox, an option group with two checkboxes allows you to choose where to search:

    • First option (default): Searches the first column (ListItem) for the given text.

    • Second option: Searches within the ListSubItem columns.

Note: Rearranging columns affects only their visual position, not the object type. Dragging a ListSubItem into the first column does not convert it into a ListItem.

To retrieve a value from a specific column, select the column name from the ComboBox located below the search-text TextBox. For example, to find a student’s Height, select Height from the ComboBox.

After setting the search criteria, click the Find Item Command Button. If the search is successful, the result will appear in the large Label control below the button.

The [Find Item] Command Button Click.

Calls the SearchAndFind() Procedure.

Private Sub SearchAndFind()
'Find by Student Name
Dim lstItem As MSComctlLib.ListItem
Dim strFind As String
Dim strColName As String
Dim strColVal As String
Dim j As Integer
Dim intOpt As Integer
Dim msgText As String

Me.Refresh
intOpt = Me.Opts


strFind = Nz(Me![txtFind], "")
strColName = Nz(Me![txtCol], "")

Select Case intOpt
    Case 1
        Set lstItem = lvwList.FindItem(strFind, , , lvwPartial)
    
        If Not lstItem Is Nothing Then
            j = lstItem.Index
            'format the display text
            msgText = lvwList.ColumnHeaders.Item(1).Text
            msgText = msgText & " : " & lstItem.Text & vbCr & vbCrLf
        Else
            MsgBox "Text '" & strFind & "' Not Found!", vbOKOnly + vbCritical, "cmdFind_Click()"
            Exit Sub
        End If
    Case 2
        Set lstItem = lvwList.FindItem(strFind, lvwSubItem, , lvwPartial)
        If Not lstItem Is Nothing Then
       'format the display text
            j = lstItem.Index
            msgText = lvwList.ColumnHeaders.Item(1).Text
            msgText = msgText & ": " & lstItem.Text & vbCr & vbCrLf
        Else
            MsgBox strFind & " Not Found!", vbOK + vbCritical, "cmdFind_Click()"
            Exit Sub
        End If
End Select

        If Len(strColName) = 0 Then 'If column name is not selected
            GoTo nextStep
        Else
            'Get the column value
            strColVal = GetColVal(lstItem, strColName)
            msgText = msgText & String(8 - (Len(strColName)), " ") & _
            strColName & ": " & Nz(strColVal, "")
        End If
nextStep:

If Len(msgText) > 0 Then 'assign to form label
    lvwList.ListItems.Item(j).Selected = True
    lblMsg.caption = msgText
End If

End Sub

At the beginning of the program, the Student Name and the optional Column Name are copied from their respective TextBoxes into the variables strFind and strColName, following validation checks.

Note: The Column Name ComboBox has its Not-in-List property set to Yes. This means you may either select a valid value from the list, type it in, or leave it blank. However, if you type in a value that does not exist in the list, it will not be accepted.

Depending on the selected search option (1 – ListItem or 2 – ListSubItem), the scan process is moved to the appropriate object(s).

Using either method, the program locates the ListItem object (row) that contains the search text. The ListItem Index value is then saved in the variable J for later use in the program.

Note: The ListView control automatically assigns index numbers when items are first populated.

Once found, the ListItem.Text value is retrieved. This value is combined with the first column header’s text (for example, Student: Robert King) and stored in the MsgText string, which is then displayed in the Label control on the form.

If a column header name is selected in the ComboBox, the program calls the GetColVal() function, passing the ListItem object and the selected column header text as parameters. This feature is especially useful for retrieving additional details about a student, such as their Height, directly from the record.

The GetColVal() Function VBA Code.

Private Function GetColVal(lvwItem As MSComctlLib.ListItem, ByVal colName As String) As String
Dim i As Integer
Dim strVal As String
    'first column is student name
    'check for column value from 2nd column onwards
    For i = 2 To lvwList.ColumnHeaders.Count
        If lvwList.ColumnHeaders(i).Text = colName Then 'if col name matches
            strVal = lvwItem.ListSubItems.Item(i - 1).Text 'get column value
            Exit For 'No further scanning required
        End If
    Next
GetColVal = strVal 'return the retrieved the value
End Function

The GetColVal() function requires two parameters:

  1. The ListItem object, which contains the student’s name.

  2. The Column Name to be retrieved.

The student’s details—such as Age, Height, Weight, and Class—are stored in the ListItem.ListSubItems collection. The function scans through the lvwList.ColumnHeader values to locate the matching column name.

Once a match is found, the corresponding column index is used to retrieve the value from the ListSubItems object and returned to the calling procedure.

The [Find By Key] Command Button Click Event Procedure.

We have introduced another method to find a Student’s Name (or related information) by using the Unique Key Value assigned to a list item at the time of creating the list.

Although assigning a Key is optional, add a Unique Key String Value (note: the key must begin with an alphabet character). This approach makes searching more efficient.

For example, when dealing with personal identification records, the following can serve as the Key:

  • Social Security Number

  • National Identity Card Number

  • Passport Number

  • Driving License Number

Using identifiers as the ListItem Key makes it much faster and easier to locate a record compared to the conventional search-by-text method.

The cmdKey_Click() Event Procedure.

Calls FindByKey() Subroutine.
Private Sub FindByKey()
Dim colHeader As MSComctlLib.ColumnHeader
Dim lvItem As MSComctlLib.ListItem
Dim lvKeyVal As String
Dim lvColName As String
Dim txt As String
Dim msgText As String
Dim varcolVal As Variant

lvKeyVal = UCase(Nz(Me!txtKey, ""))
lvColName = Nz(Me!txtCol, "")

If len(lvKeyVal) > 0 then
On Error Resume Next 
Set lvItem = lvwList.ListItems.Item(lvKeyVal) 'get the item by Key
If Err > 0 Then
    Err.Clear
    MsgBox "Key Value: '" & lvKeyVal & "' Not Found!", vbOKOnly + vbCritical, "cmdKey_Click()"
    On Error GoTo 0
    Exit Sub
End If
Else
	MsgBox "Please Provide a Valid Key-Value!",vbOKOnly + vbCritical, "cmdKey_Click()"
    Exit Sub
End If

txt = lvItem.Text 'get the student name
'format message text
msgText = lvwList.ColumnHeaders.Item(1).Text & " : "
msgText = msgText & txt & vbCr & vbCrLf

If Len(lvColName) > 0 Then 'if column name is given
    varcolVal = GetColVal(lvItem, lvColName) 'get column val of student
    msgText = msgText & String(8 - Len(lvColName), " ") & lvColName & ": " & varcolVal ' add it to display
End If

lvItem.Selected = True 'highlight the item on form
Me.lblMsg.caption = msgText 'assign details to form Label
End Sub

As shown in the subroutine, we can directly locate the ListItem containing the Student’s name by using the Key value in a single statement:

Set lvItem = lvwList.ListItems.Item(xKeyVal)

The next line retrieves the ListItem.Text (the Student’s name) into the variable txt. The following two lines then build the message string by inserting the Student’s name into the variable msgText.

Next, an If…Then statement checks whether a Column Name has been entered in the ComboBox control. If a valid column is found, the program calls the GetColVal() function with the appropriate parameters to retrieve the value from that column. The returned value is stored in the variable varColVal and passed back to the calling procedure.

Finally, the Column Name and the retrieved value are appended to the msgText string, which is then displayed in the Label control on the Form.

The next statement highlights the Student’s record row as a visual cue that the searched item has been found. At the same time, the value stored in msgText is displayed in the Label control by setting its Caption property on the Form.

The Full VBA code on the Form Module.

Option Compare Database
Option Explicit

Dim lvwList As MSComctlLib.ListView 'ListView Control
Dim lvwItem As MSComctlLib.ListItem '
Dim ObjImgList As MSComctlLib.ImageList
Const prfx As String = "K"

Private Sub Form_Load()
    Call LoadListView
    Call txtColCombo
End Sub

Private Function LoadListView()
'Populate the ListView control with Student Details
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim intCounter As Integer
Dim strKey As String

'Assign ListView Control on Form to lvwList Object
 Set lvwList = Me.ListView1.Object
 
With lvwList
    .AllowColumnReorder = True
    .Enabled = True
    .Font = "Verdana"
    .Font.Bold = True
    .Font.Size = 9
    .ForeColor = vbBlack
    .BackColor = vbWhite
 End With
 
 'Create Column Headers for ListView
 With lvwList
    .ColumnHeaders.Clear 'initialize header area
    
   'Syntax: .ColumnHeaders.Add Index, Key, Text, Width, Alignment, Icon
    .ColumnHeaders.Add , , "Student", 2500
    .ColumnHeaders.Add , , "Age", 1200
    .ColumnHeaders.Add , , "Height", 1200
    .ColumnHeaders.Add , , "weight", 1200
    .ColumnHeaders.Add , , "Class", 1200
    
 End With
 
 'Initialize ListView Control
  While lvwList.ListItems.Count > 0
        lvwList.ListItems.Remove (1)
  Wend

'Student Names and Ids are taken from Employees Table
'through the StudentQ Query.
Set db = CurrentDb
Set rst = db.OpenRecordset("StudentQ", dbOpenDynaset)

With lvwList
    Do While Not rst.EOF And Not rst.BOF
        intCounter = rst![EmployeeID]
        strKey = "X" & Format(intCounter, "00") 'Key Value sample: X01
        
    'Syntax: .ListItems.Add(Index, Key, Text, Icon, SmallIcon)
        Set lvwItem = .ListItems.Add(, strKey, rst![Student])
        
        With lvwItem
    'Syntax: .Add Index,Key,Text,Report Icon,TooltipText
            .ListSubItems.Add , strKey & CStr(intCounter), CStr(5 + intCounter)
            .ListSubItems.Add , strKey & CStr(intCounter + 1), CStr(135 + intCounter)
            .ListSubItems.Add , strKey & CStr(intCounter + 2), CStr(40 + intCounter)
            .ListSubItems.Add , strKey & CStr(intCounter + 3), ("Class:" & Format(intCounter, "00"))

       End With
        rst.MoveNext
    Loop
rst.Close
Set rst = Nothing
Set db = Nothing
Set lvwItem = Nothing
End With
lvwList.Refresh

End Function


Private Sub cmdClose_Click()
   DoCmd.Close acForm, Me.Name
End Sub

Private Sub cmdFind_Click()
Call SearchAndFind

End Sub

Private Sub cmdKey_Click()
Call FindByKey
End Sub

Private Function GetColVal(lvwItem As MSComctlLib.ListItem, ByVal colName As String) As String
Dim i As Integer
Dim strVal As String
    'first column is student name
    'check for column value from 2nd column onwards
    For i = 2 To lvwList.ColumnHeaders.Count
        If lvwList.ColumnHeaders(i).Text = colName Then 'if col name matches
            strVal = lvwItem.ListSubItems.Item(i - 1).Text 'get column value
            Exit For 'No further scanning required
        End If
    Next
GetColVal = strVal 'return the retrieved the value
End Function



Private Sub txtColCombo()
'Column Header List Combo
Dim lvwColHead As MSComctlLib.ColumnHeader
Dim cboName As ComboBox

Set cboName = Me.txtCol
cboName.RowSourceType = "Value List"

For Each lvwColHead In lvwList.ColumnHeaders
    If lvwColHead.Index = 1 Then
        'Nothing
    Else
        cboName.AddItem lvwColHead.Text
    End If
Next
'cboName.DefaultValue = "=txtCol.Column(0, 0)"

Set lvwColHead = Nothing
Set cboName = Nothing
End Sub


Public Sub SearchAndFind()
'Find by Student Name
Dim lstItem As MSComctlLib.ListItem
Dim strFind As String
Dim strColName As String
Dim strColVal As String
Dim j As Integer
Dim intOpt As Integer
Dim msgText As String

Me.Refresh
intOpt = Me.Opts

strFind = Nz(Me![txtFind], "")
strColName = Nz(Me![txtCol], "")

Select Case intOpt
    Case 1
        Set lstItem = lvwList.FindItem(strFind, , , lvwPartial)
        If Not lstItem Is Nothing Then
            j = lstItem.Index
            'format the display text
            msgText = lvwList.ColumnHeaders.Item(1).Text
            msgText = msgText & " : " & lstItem.Text & vbCr & vbCrLf
        Else
           MsgBox "Text '" & strFind & "' Not Found in the List!", vbOKOnly + vbCritical, "cmdFind_Click()"
        Exit Sub
        End If
    Case 2
        Set lstItem = lvwList.FindItem(strFind, lvwSubItem, , lvwPartial)
        If Not lstItem Is Nothing Then
       'format the display text
            j = lstItem.Index
            msgText = lvwList.ColumnHeaders.Item(1).Text
            msgText = msgText & ": " & lstItem.Text & vbCr & vbCrLf
        Else
            MsgBox strFind & " Not Found!", vbOK + vbCritical, "cmdFind_Click()"
            Exit Sub
        End If
End Select

        If Len(strColName) = 0 Then 'If column name is not selected
            GoTo nextStep
        Else
            'Get the column value
            strColVal = GetColVal(lstItem, strColName)
            msgText = msgText & String(8 - (Len(strColName)), " ") & _
            strColName & ": " & Nz(strColVal, "")
        End If
nextStep:

If Len(msgText) > 0 Then 'assign to form label
    lblMsg.caption = msgText
    lvwList.ListItems.Item(j).Selected = True
End If
End Sub

Public Sub FindByKey()
Dim colHeader As MSComctlLib.ColumnHeader
Dim lvItem As MSComctlLib.ListItem
Dim lvKeyVal As String
Dim lvColName As String
Dim txt As String
Dim msgText As String
Dim varcolVal As Variant


lvKeyVal = UCase(Nz(Me!txtKey, ""))
lvColName = Nz(Me!txtCol, "")

On Error Resume Next
If Len(lvKeyVal) > 0 Then
Set lvItem = lvwList.ListItems.Item(lvKeyVal) 'get the item by Key
    If Err > 0 Then
        Err.Clear
        MsgBox "Key Value: '" & lvKeyVal & "' Not Found!", vbOKOnly + vbCritical, "cmdKey_Click()"
       On Error GoTo 0
        Exit Sub
    End If
Else
    MsgBox "Please Provide a Valid Key-Value!", vbOKOnly + vbCritical, "cmdKey_Click()"
    Exit Sub
End If

txt = lvItem.Text 'get the student name
'format message text
msgText = lvwList.ColumnHeaders.Item(1).Text & " : "
msgText = msgText & txt & vbCr & vbCrLf

If Len(lvColName) > 0 Then 'if column name is given
    varcolVal = GetColVal(lvItem, lvColName) 'get column val of student
    msgText = msgText & String(8 - Len(lvColName), " ") & lvColName & ": " & varcolVal ' add it to display
End If

lvItem.Selected = True 'highlight the item on form
Me.lblMsg.caption = msgText 'assign details to form Label
End Sub

Download the Demo Database from the following Link:



  1. Microsoft TreeView Control Tutorial
  2. Creating an Access Menu with a TreeView Control
  3. Assigning Images to TreeView Nodes
  4. Assigning Images to TreeView Nodes-2
  5. TreeView Control Checkmark Add Delete
  6. TreeView ImageCombo Drop-down Access
  7. Rearrange TreeView Nodes By Drag and Drop
  8. ListView Control with MS-Access TreeView
  9. ListView Control Drag-and-Drop Events
  10. TreeView Control With Sub-Forms
Share:

Activex ListView Control Tutorial-01

ListView Control Tutorial.

In Microsoft Access, the ListBox control is often used for displaying a few columns of data, making it easy to locate and select items. Table or Query records the Row Source property value.

The ComboBox control, by contrast, keeps its list hidden until the user clicks to expand it and make a selection. Both of these are standard Access controls on Forms.

The Datasheet View is another familiar list-style control we encounter frequently in Access. Whether records are displayed from a table or query, the datasheet presents them as a large, scrollable list in tabular format.

In addition to these built-in controls, Microsoft Access also allows us to use ActiveX controls. A common example is the Microsoft Common Dialog Control (often used for file browsing).

The focus is on an interesting list view control, the Windows ActiveX ListView Control. Think of it as similar to Windows Explorer: it can display items as large icons, small icons, a simple list, or in a detailed view with multiple columns. Data from an Access table or query can be loaded into the ListView, giving you the ability to:

  • Rearrange columns or rows,

  • Sort items interactively,

  • Display images next to items,

  • Present records in a more flexible, customizable layout.

This control is widely used in other programming environments such as VB6, VB.NET, and C#. In this article, we will explore its usage in a Microsoft Access database.

Below is a simple ListView demo screen displaying sample data:

We will use the image-like display shown earlier as the starting point for this ListView Control tutorial. With just a few lines of VBA code, we have uploaded ten rows of data into the ListView control.

By default, the ListView ActiveX control may not appear in the list of available ActiveX controls in Access. To make it available, we must add the library file 'MSCOMCTL.OCX' from the C:\Windows\System32 folder to the Access references. Once registered, you will see it listed as Microsoft ListView Control, Version 6.0, along with other ActiveX controls.

This library file provides several useful controls, including ListView, TreeView, and ImageList. If you have already followed our earlier TreeView control tutorials, you are familiar with this library.

Adding the Windows Common Controls Library (MSCOMCTL.OCX)

Follow these steps to attach the MSCOMCTL.OCX file to your database:

  1. Open your database and press Alt+F11 to launch the VBA editor.

  2. From the Tools menu, select References…

  3. Click the Browse button.

  4. Locate the file MSCOMCTL.OCX (Microsoft Windows Common Controls) in one of the following folders:

    • C:\Windows\System32\ → on 32-bit systems or on most Windows 11 installations.

    • C:\Windows\SysWOW64\ → on 64-bit systems.

  5. Select the file and click Open to attach it to your database.

  6. Press Alt+F11 again to return to the database window.

Designing a Sample Form with the ListView Control

We will now design a simple form that matches the sample image shown at the beginning of this tutorial.

  1. Create a new blank form in Design View.

  2. From the Controls group, select ActiveX Control.

  3. In the list of available ActiveX controls, locate and select Microsoft ListView Control, Version 6.0, then click OK to insert it onto the form’s Detail section.

  4. Resize the control:

    • Grab the bottom-right resize handle and drag it outward to make the ListView large enough to resemble the sample image.

    • Move the control slightly down and to the right to leave space for a heading label above and some margin on the left.

  5. With the ListView still selected, open the Property Sheet and rename the control by setting its Name property to: ListView1

  6. Create a Label control above the ListView.

    • Change its Caption property to: ListView Control Tutorial

    • Apply any formatting you prefer (font size, bold, color, etc.) to make the heading stand out.

  7. Insert a Command Button below the ListView.

    • Set its Name property to: cmdClose

    • Set its Caption property to: Close

When completed, your form design should look similar to the following layout:

  1. Now, save the Form as ListView Tutorial and keep the Form in Design View.

  2. Press Alt+F11 to go back to the Form’s Class Module Window.

    The VBA Code.

  3. Copy and paste the following Code into the Form's VBA Module, replacing existing lines of code, if any:

    Option Compare Database
    Option Explicit
    
    Dim lvwList As MSComctlLib.ListView
    Dim lvwItem As MSComctlLib.ListItem
    Dim ObjImgList As MSComctlLib.ImageList
    Const prfx As String = "X"
    
    Private Sub cmdClose_Click()
       DoCmd.Close acForm, Me.Name
    End Sub
    
    Private Sub Form_Load()
        Call LoadListView
    End Sub
    
    Private Function LoadListView()
        Dim intCounter As Integer
        Dim strKey As String
    
    'Assign ListView Control on Form to lvwList Object
     Set lvwList = Me.ListView1.Object
     
     'Create Column Headers for ListView
     With lvwList
        .ColumnHeaders.Clear 'initialize header area
       'Parameter List:
    'Syntax: .ColumnHeaders.Add Index, Key, Text, Width, Alignment, Icon
        .ColumnHeaders.Add , , "Name", 2500
        .ColumnHeaders.Add , , "Age", 1200
        .ColumnHeaders.Add , , "Height", 1200
        .ColumnHeaders.Add , , "weight", 1200
        .ColumnHeaders.Add , , "Class", 1200
     End With
     
     'Initialize ListView Control
      While lvwList.ListItems.Count > 0
            lvwList.ListItems.Remove (1)
      Wend
        
     With lvwList
        For intCounter = 1 To 10
            strKey = prfx & CStr(intCounter) '
       'Syntax: .ListItems.Add(Index, Key, Text, Icon, SmallIcon)
            Set lvwItem = .ListItems.Add(, strKey, "Student " & intCounter)
            'Add next columns of data as sub-items of ListItem
            With lvwItem
          'Parameters =      .Add Index,Key,Text,Report Icon,TooltipText
                .ListSubItems.Add , strKey & CStr(intCounter), CStr(5 + intCounter)
                .ListSubItems.Add , strKey & CStr(intCounter + 1), CStr(135 + intCounter)
                .ListSubItems.Add , strKey & CStr(intCounter + 2), CStr(40 + intCounter)
                .ListSubItems.Add , strKey & CStr(intCounter + 3), ("Class:" & intCounter)
    
           End With
        Next
        'reset lvwItem object
        Set lvwItem = Nothing
    End With
    lvwList.Refresh
    
    End Function
  4. Save the Form with the name ListView Control Tutorial-01.

    Demo View of the Form.

  5. Open the Form in Normal View to have a look at our creation.

    If the Form View is similar to the one below, then you are on the right track.

    The ListView Control's Property Settings must be assigned correctly to view the control the way we want. Earlier, we renamed the control to ListView1 using the standard Access Property Sheet. However, the ListView control has its own dedicated property sheet, which gives more detailed configuration options. Some of these settings also appear in the Access Property Sheet, but many are unique to the control itself.

  6. To access it, right-click the ListView control, point to ListViewCtrl Object, and then select Properties from the shortcut menu.

  7. This will open the ListView control’s own property sheet, as shown in the image below:

  8. At the top of the Property Sheet, you will see tabs that group various options. By default, the General tab is active. On this tab, the left side lists option values, while the right side contains corresponding checkboxes.

    For our form, we only need to adjust two ListView properties, which are disabled by default. Once enabled, these allow the ListView to display in different modes—such as large icons, small icons, simple lists, or Report View (as shown in the first image above).

    1. Check the Enabled property on the right side to activate the ListView control.

    2. From the View drop-down list on the left side, select lvwReport.

    3. Click the Apply button to confirm the change.

    4. Click OK to close the Property Sheet.

    Finally, save the Form and open it in Normal View. The result should now look like the image shown earlier, except for any differences in Form background color or other Form-level settings.

  9. The Program's Functional Diagram.

    Before diving into the VBA code, it’s important to understand how data items are actually loaded into the ListView control. With a ListBox, the data arrangement is fairly straightforward. However, the ListView control uses a completely different approach. The loading process doesn't follow the logical sequence we might naturally expect.

    Once you see how the data flows from the source into a single row—illustrated as a diagram or flow chart—the concept becomes much easier to grasp. With this visual in mind, understanding  VBA code and its role in the process will be far more intuitive.

    The Data Flow Diagram.

    1. In the diagram, the box at the top-left corner represents the ListView control.

      The first step in preparing the list is to create the column headings. These headings (shown in red in the diagram) work the same way as field headers in a table’s Datasheet View. Each column heading is added to the ColumnHeaders collection of the ListView control using the ColumnHeaders.Add() method. Since our sample has five columns, the method is called five times, once for each heading.

      The next set of actions loads the actual data. Each row of data represents a single record with five fields. However, these fields are not loaded all at once—they are split between two different object members of the ListView control: ListItems and ListSubItems.

      • The first field value (the value for the first column) is added to the ListItems collection using the ListItems.Add method. For example, in the sample image, the value Student1 (from the first column of the first row) is stored in the ListItems object.

      • From the second column onward, the remaining field values are added as ListSubItems of the corresponding ListItem. This is done using the ListSubItems.Add method, called four times—once each for the Age, Height, Weight, and Class values.

      Together, these two steps complete a single row of data in the ListView control. The diagram illustrates this process with two rows of sample data.

      Once you understand this two-level structure—ListItems for the first column, ListSubItems for the remaining fields—the VBA code that builds the ListView will be much easier to follow.

    Let us go through the VBA code.

    In the VBA Module global declaration section, we have declared the ListView object, the ListItem object, the ImageList object, and a constant variable with the string value "LV".

    Dim lvwList As MSComctlLib.ListView
    Dim lvwItem As MSComctlLib.ListItem
    Dim ObjImgList As MSComctlLib.ImageList
    Const prfx As String = "X"


    The variable lvwList is declared as a ListView object, lvwItem as a ListItem object of the ListView control, and ObjImgList as an ImageList object. The ImageList object is another ActiveX control that can store image icons for use with both the TreeView and ListView controls. For now, we will set the ImageList aside and return to it later.

    The constant Prfx is used as the Key value prefix in the ListItems.Add method, which accepts several optional parameters. The Key value must always be a string type.

    The LoadListView() function serves as the main program.

    On our Form, the ListView control is named ListView1. The first executable statement in the program is:

    Set lvwList = Me.ListView1.Object 

      Assigns the ListView1 control on the Form to the Object variable lvwList declared in the Global declarations area.

      Next, we prepare to load the Column Header information.  First, we initialize the ColumnHeader object to ensure that it is empty.  When we run the program repeatedly, the control retains the earlier loaded values in the ColumnHeader control.  When you open and close the Form multiple times with the ColumnHeaders.Clear statement disabled, you will notice the difference: the same set of headings is added to the control each time, resulting in empty rows appearing beneath them.

    You can verify this behavior manually with the following steps:

    1. Open the demo form once and then close it.

    2. Reopen the form in Design View.

    3. Right-click the ListView control, highlight the ListViewCtrl Object option, and select Properties from the menu.

    4. In the property sheet, go to the Column Headers tab.

    5. You will see the first column heading displayed in a text box, with its Index value (1) shown above.

    6. Move the mouse pointer to the right side of the index number box. Arrow buttons (left and right) will appear.

    7. Click the right arrow to scroll through and display the remaining column labels, one by one, as their index numbers change.

    8. If you open and close the form again, you will notice that the Column Headers tab now contains duplicate sets of the same column labels.

    The ColumnHeaders.Add method syntax is as follows:
    lvwList.ColumnHeaders.Add(Index, Key, Text, Width, Alignment, Icon)

    All parameters are optional.

    With lvwList
        .ColumnHeaders.Clear 'initialize header area
    'Parameter List:
    'Syntax: .ColumnHeaders.Add Index, Key, Text, Width, Alignment, Icon
        .ColumnHeaders.Add , , "Name", 2500
        .ColumnHeaders.Add , , "Age", 1200
        .ColumnHeaders.Add , , "Height", 1200
        .ColumnHeaders.Add , , "weight", 1200
        .ColumnHeaders.Add , , "Class", 1200
     End With 

    The Index value is automatically assigned as running serial numbers (1, 2, 3, and so on).

    The Key value is a String data Type. It is not typically used for a column header.

    The Text value is what appears on the control as the column label.

    To control the display width of each column, you can assign an approximate width value in pixels, based on the data expected under that column.

    If the Text alignment property is omitted, the default is Left alignment (0 - lvwAlignmentLeft). Alternatively, you can set it to Right alignment (1 - lvwAlignmentRight) or Center alignment (2 - lvwAlignmentCenter).

    Once the column headings are loaded, the next step inserts the first record. Specifically, we start by loading the value in the first column of the first row. But before doing so, we must initialize the ListItems object with the following code segment:

    'Initialize ListView Control
      While lvwList.ListItems.Count > 0
            lvwList.ListItems.Remove (1)
      Wend

    The next code block loads the record list items one row at a time, and a total of ten rows with sample values. For demonstration purposes, these values remain mostly constant, with a few variations to highlight the process. This is accomplished by placing the logic inside a For... Next Loop, which iterates ten times, thereby creating ten rows of data in the ListView control.

    With lvwList
        For intCounter = 1 To 10
            strKey = prfx & CStr(intCounter) '
      'Syntax: .ListItems.Add(Index, Key, Text, Icon, SmallIcon)
            Set lvwItem = .ListItems.Add(, strKey, "Student " & intCounter)
            
      'Add next columns of data as sub-items of ListItem
            With lvwItem
      ' Syntax: .ListSubItems.Add Index,Key,Text,Report Icon,TooltipText
                .ListSubItems.Add , strKey & CStr(intCounter), CStr(5 + intCounter)
                .ListSubItems.Add , strKey & CStr(intCounter + 1), CStr(135 + intCounter)
                .ListSubItems.Add , strKey & CStr(intCounter + 2), CStr(40 + intCounter)
                .ListSubItems.Add , strKey & CStr(intCounter + 3), ("Class:" & intCounter)
    
           End With
        Next
        'reset lvwItem object
        Set lvwItem = Nothing
    End With

    The first statement inside the For...Next loop —

    strKey = prfx & CStr(intCounter)

    — prepares a unique Key value for the first list item (the first column).

    All parameters of the ListItems.Add() Methods are optional. However, in this case, the first three—Index, Key, and Text—are used in the same sequence as the Column Headers. The remaining two parameters are reserved for assigning an icon and a small icon image, if needed.

    When the value for the first column of a row is assigned to the ListItem (i.e., lvwList.ListItems), that object reference is stored in the lvwItem variable. This allows easy access to its sub-object, ListSubItems, without repeatedly writing the full object reference.

    lvwList.ListItems.Item(index).ListSubItems.Add() 

    Expressed in the short form with lvwItem.ListSubItems.Add()

    Using the short form 'lvwItem.ListSubItems.Add()' We can load the remaining column values into the ListView control.

    The ListSubItems.Add() method accepts its first three parameters in the same order as the ListItem (Index, Key, and Text), followed by the optional Icon image reference and Tooltip Text.

    For each column Key value, I have appended the current loop counter value plus an offset to ensure uniqueness across all columns. Although the Key parameter can be omitted, it is good practice to use it.

    The Method  ListSubItems.Add()  is called four times within the loop to insert values for the second through fifth columns.

    These steps repeat nine more times, ultimately creating ten sample records in the ListView control.

    The demo database containing this ListView control example is attached, ready to run and explore.

    In the next part of this tutorial, we will explore how to search and locate specific values within the ListView control, as well as how to rearrange columns—just like we do in Datasheet View.

    1. Microsoft TreeView Control Tutorial
    2. Creating an Access Menu with a TreeView Control
    3. Assigning Images to TreeView Nodes
    4. Assigning Images to TreeView Nodes-2
    5. TreeView Control Checkmark Add Delete
    6. TreeView ImageCombo Drop-down Access
    7. Rearrange TreeView Nodes By Drag and Drop
    8. ListView Control with MS-Access TreeView
    9. ListView Control Drag-and-Drop Events
    10. TreeView Control With Sub-Forms
Share:

MS-Access And Transfer SpreadSheet Command.

Export MS Access Tables to a Spreadsheet.

A very useful feature of Microsoft Access is the ability to transfer data between Access and Excel using the built-in Import/Export options. In this session, we will focus on the Export process and examine the challenges that may arise after exporting data, particularly when using various export options available in MS Access.

The simple VBA Command Syntax is:

Docmd.TransferSpreadsheet [Transfer Type],[SpreadSheet Type], _
	[Input TableName/Query Name],[Output FilePath], _
	True(HasFieldNames),Range,UseOA
  1. The first parameter, [Transfer Type] can take one of two values: acImport or acExport.

    The second parameter Spreadsheet Type accepts predefined options ranging from 0 to 10. These are part of an enumerated list that includes support for Lotus worksheets.

    The available options are:

    • acSpreadsheetTypeExcel12Xml – 10

    • acSpreadsheetTypeExcel12 – 9

    • acSpreadsheetTypeExcel9 – 8

    • acSpreadsheetTypeExcel8 – 8

    • acSpreadsheetTypeExcel7 – 5

    • acSpreadsheetTypeExcel5 – 5

    • acSpreadsheetTypeExcel4 – 6

    • acSpreadsheetTypeExcel3 – 0

    • acSpreadsheetTypeLotusWJ2 – 4

    • acSpreadsheetTypeLotusWk4 – 7

    • acSpreadsheetTypeLotusWk3 – 3

    • acSpreadsheetTypeLotusWk1 – 2

    You can pass either the enumeration name or its corresponding numeric value as the second parameter.

  2. The third parameter specifies the name of the input Table or Query to be exported (or imported).

  3. The fourth parameter is the full path and file name of the output spreadsheet.

  4. The fifth parameter is a Boolean value (True or False). Setting it to True ensures that the field names are included as the first row in the exported worksheet.

  5. The optional Range parameter applies only when using acImport, allowing you to define the worksheet range from which data should be imported.

  6. The final optional parameter UseOA is not defined and is typically not used.

Sample Transfer-Spreadsheet Command.

Docmd.TransferSpreadSheet acExport,acSpreadSheetTypeExcel12xml, _
  ”Products”,”C:\My Documents\Book1.xlsx”,True
  • The options acSpreadsheetTypeExcel3 through acSpreadsheetTypeExcel9 create files in the Excel 97–2003 format with the .xls extension. These files can still be opened in Excel 2007, but if you explicitly use the output file type with the .xlsx extension, the file will not open in Excel 2007 or later versions of Excel.

  • The option acSpreadsheetTypeExcel12 creates a file with the .xlsb extension. This is a binary-coded Excel file, fully compatible with Excel 2007 and above. It is especially useful for exporting large volumes of records as it produces a significantly smaller file size.

  • The option acSpreadsheetTypeExcel12Xml (note: often written as Excel12Xml) produces a file with the .xlsx extension, also compatible with Excel 2007 and higher.

  • When using acSpreadsheetTypeExcel9 or earlier, the exported file is functional. Still, it inherits the older Office 2003 theme, which can appear outdated in style compared to modern versions — as shown in the sample screenshot below.

Normally, after exporting, you may need to open the output file in your current version of Excel, update the formatting (such as font and font size), and then save it again in the latest Excel format. If you simply add the .xlsx extension to the target file name in the TransferSpreadsheet Command, expecting Excel 2007 or higher to recognize it automatically, the file will fail to open in those versions.

However, there is a simple trick to overcome this limitation. Using this method, the exported file will always be saved in the current version of Excel installed on your system — whether it is Excel 2007, 2010, 2013, or newer — regardless of which worksheet type you selected in the TransferSpreadsheet command.

A Simple Solution

  1. First, create a blank Excel Workbook in your current version of Excel and save it in the desired target location.

  2. Close the Workbook.

  3. Run the TransferSpreadsheet command, using the saved Workbook’s file path as the target file parameter.

The exported data will be placed into a new worksheet within that Workbook. Since the Workbook was originally created in your current Excel version, the output will automatically adopt the default Office Theme of that version. This ensures that your exported data looks modern and properly formatted, as shown in the sample image below:

We have created three slightly different functions, each designed to save the output of the TransferSpreadsheet command distinctly.

The Export2ExcelA() Function.

The above Function creates a single WorkSheet as output in the target workbook.

Public Function Export2ExcelA(ByVal xlFileLoc As String, ByVal QryORtableName As String) As String
On Error GoTo Export2ExcelA_Err
Dim tblName As String
Dim filePath As String
Dim xlsPath As String

Dim wrkBook As Excel.Workbook

'xlFileLoc = "D:\Blink\tmp2\"
'QryORtblName = "Products"

xlsPath = xlFileLoc & QryORtableName & ".xlsx"
If Len(Dir(xlsPath)) = 0 Then
    Set wrkBook = Excel.Workbooks.Add
        wrkBook.SaveAs xlsPath
        wrkBook.Close
End If
DoCmd.TransferSpreadSheet acExport, acSpreadsheetTypeExcel12Xml, QryORtableName, xlsPath, True

MsgBox "File: " & xlsPath & " Created ", , "Export2ExcelA()()"

Set wrkBook = Nothing
Export2ExcelA = xlsPath

Export2ExcelA_Exit:
Exit Function

Export2ExcelA_Err:
MsgBox Err & " : " & Err.Description, , "Export2ExcelA()"
Export2ExcelA = ""
Resume Export2ExcelA_Exit

End Function

The Export2ExcelA() function requires two parameters:

  1. The target path of the output Excel file.

  2. The name of the input Table or Query.

In this example, the function exports data from the Products table, creating a worksheet in a workbook saved at the specified location.

At the start of the code, the function checks whether an Excel file with the specified name already exists.

  • If the file does not exist, a new workbook is created in the current version of Excel. The workbook is saved using the same name as the input table/query and then closed.

  • If the file already exists, the output worksheet is simply added to that workbook.

Now, what happens if we don’t pre-create a workbook in the current Excel version?

  • If no file extension is provided (e.g., C:\My Documents\Products) and the SpreadsheetTypeExcel9 option is selected, Access creates a new file with an .xls extension (Products.xls).

  • If the .xlsx extension is explicitly specified with SpreadsheetTypeExcel9, the command still creates the file, but it will not open in Excel 2007 or higher versions.

  • However, if an existing workbook (e.g., C:\My Documents\myBook.xlsx) is available, the exported data is added as a new worksheet. In this case, the sheet automatically inherits the current version of Excel's default Office theme.

This is why we explicitly create a new workbook in the current Excel version and save it to the target location in advance. Once saved, the workbook must be closed before referencing it in the TransferSpreadsheet command’s output file parameter.

Important: If the target workbook is open when the command executes, an error will occur (“Source file not found”). The workbook must not be in use to avoid this issue.

Finally, the workbook pathname is passed to the TransferSpreadsheet command, and the export is completed successfully.

Export Options:

  1. Creating Separate Worksheets in a Single Workbook.
  2. Exporting Data into Separate Worksheets or Workbooks

Often, we need to export grouped subsets of data into Excel for reporting or distribution. For example:

  • Each region’s sales report is in a separate worksheet of a single workbook.

  • Each employee’s performance report is in a separate workbook.

  • Or, in our example, products are grouped by category into individual worksheets.

Using the Products table from the Northwind sample database, we’ll demonstrate how to export product data by category.

We can approach this requirement in two ways:

  1. Separate Worksheets in a Single Workbook

    • A single workbook (e.g., ProductsByCategory.xlsx).

    • Each worksheet corresponds to a product category.

  2. Separate Workbooks per Category

    • Each product category is exported into its own Excel file.

    • E.g., Beverages.xlsx, Condiments.xlsx, etc.

The Export2ExcelB() Function VBA Code:

Public Function Export2ExcelB(ByVal xlFileLoc As String, ByVal QryORtableName As String) As String
'----------------------------------------------------------------
'Creates separate Excel WorkBook for each Group of Records
'based on changing Query criteria.
'Uses Query Name Used for workBook Name
'----------------------------------------------------------------
On Error GoTo Export2ExcelB_Err
Dim strSQL As String
Dim m_min As Integer, m_max As Integer
Dim j As Integer
Dim qryName As String
Dim qryDef As QueryDef
Dim db As Database, rst As Recordset

Dim xlsPath As String
Dim xlsName As String
Dim wrkBook As Excel.Workbook

m_min = CInt(DMin("seq", "QryParam"))
m_max = CInt(DMax("seq", "QryParam"))

    xlsName = QryORtableName & ".xlsx"
    xlsPath = xlFileLoc & xlsName
    
If Len(Dir(xlsPath)) > 0 Then
    Kill xlsPath
End If

    Set wrkBook = Excel.Workbooks.Add
    wrkBook.SaveAs xlsPath
    wrkBook.Close
        
Set db = CurrentDb
For j = m_min To m_max

strSQL = "SELECT Products.[Product Code], QryParam.Category, " & _
"Mid([Product Name],19) AS ProductName, Products.[Standard Cost], " & _
"Products.[List Price], Products.[Quantity Per Unit] " & _
"FROM QryParam INNER JOIN Products ON QryParam.Category = Products.Category " & _
"WHERE (((QryParam.Seq)= " & j & "));"

qryName = "Category_" & Format(j, "000")
On Error Resume Next
Set qryDef = db.CreateQueryDef(qryName)
If Err Then
   Err.Clear
   Set qryDef = db.QueryDefs(qryName)
End If
On Error GoTo 0
    qryDef.SQL = strSQL
    db.QueryDefs.Refresh
    
    DoCmd.TransferSpreadSheet acExport, acSpreadsheetTypeExcel12Xml, qryName, xlsPath, True
   
    db.QueryDefs.Delete qryName
Next
    MsgBox m_max & " Excel WorkSheets Created " & vbCr & "in Folder: " & xlsPath, , "Export2ExcelB()"
    Set wrkBook = Nothing
    Export2ExcelB = xlsPath
    
Export2ExcelB_Exit:
Exit Function

Export2ExcelB_Err:
MsgBox Err & " : " & Err.Description, , "Export2ExcelB()"
Export2ExcelB = ""
Resume Export2ExcelB_Exit
End Function
  • Instead of creating a new workbook for each loop iteration,

  • You now create the workbook once before the loop starts,

  • Then inside the For...Next loop, you export each category’s products as a new worksheet into that same workbook.

That way, the end result is:

  • One Excel file (e.g., ProductsByCategory.xlsx).

  • Inside it, multiple worksheets, one per product category.

  • Each worksheet holds the data filtered by its category.

Here’s a refined explanation of that step:

Exporting Multiple Worksheets into a Single Workbook

In the revised code, we first create and save an empty Excel workbook at the target location. This ensures the workbook is in the current Excel version and theme.

Once the workbook is ready, we use a For...Next loop to go through each product category. For every category:

  1. A query (or SQL statement) filters the products for that category.

  2. The TransferSpreadsheet command exports the filtered dataset into the prepared workbook.

  3. Each export creates a new worksheet inside the same workbook.

Because the workbook creation step is outside the loop, only one workbook is created, while multiple worksheets are added as the loop runs.

All Output Worksheets in Different Workbooks.

  1. Loop through categories in the Products table.

  2. Inside the loop, create a new workbook in the current Excel version.

  3. Immediately close the workbook (to release the file lock).

  4. Call DoCmd.TransferSpreadsheet, passing the new workbook’s path.

  5. The export command writes the category’s data as a single worksheet in that workbook.

This way:

  • Each category’s data lives in its own Excel file.

  • Useful when you need to distribute different files to different departments, customers, or teams.

The Export2ExcelC() Function VBA Code:

Public Function Export2ExcelC(ByVal xlFileLoc As String) As String
'----------------------------------------------------------------
'Creates separate Excel WorkBook for each Group of Records
'based on changing Query criteria.
'Uses Query Name Used for workBook Name
'----------------------------------------------------------------
On Error GoTo Export2ExcelC_Err
Dim strSQL As String
Dim m_min As Integer, m_max As Integer
Dim j As Integer
Dim qryName As String
Dim qryDef As QueryDef
Dim db As Database, rst As Recordset

Dim xlsPath As String
Dim xlsName As String
Dim wrkBook As Excel.Workbook

m_min = CInt(DMin("seq", "QryParam"))
m_max = CInt(DMax("seq", "QryParam"))

Set db = CurrentDb
For j = m_min To m_max

strSQL = "SELECT Products.[Product Code], QryParam.Category, " & _
"Mid([Product Name],19) AS ProductName, Products.[Standard Cost], " & _
"Products.[List Price], Products.[Quantity Per Unit] " & _
"FROM QryParam INNER JOIN Products ON QryParam.Category = Products.Category " & _
"WHERE (((QryParam.Seq)= " & j & "));"

qryName = "Category_" & Format(j, "000")
On Error Resume Next
Set qryDef = db.CreateQueryDef(qryName)
If Err Then
   Err.Clear
   Set qryDef = db.QueryDefs(qryName)
End If
On Error GoTo 0
    qryDef.SQL = strSQL
    db.QueryDefs.Refresh

        xlsName = qryName & ".xlsx"
        xlsPath = xlFileLoc & xlsName
        Set wrkBook = Excel.Workbooks.Add
        wrkBook.SaveAs xlsPath
        wrkBook.Close
    
    DoCmd.TransferSpreadSheet acExport, acSpreadsheetTypeExcel12Xml, qryName, xlsPath, True
   
    db.QueryDefs.Delete qryName
Next
    MsgBox m_max & " Excel Files Created " & vbCr & "in Folder: " & xlFileLoc, , "CreateXLSheets()"
    Set wrkBook = Nothing
    Export2ExcelC = xlFileLoc & qryName & ".xlsx"

Export2ExcelC_Exit:
Exit Function

Export2ExcelC_Err:
MsgBox Err & " : " & Err.Description, , "Export2ExcelC()"
Export2ExcelC = ""
Resume Export2ExcelC_Exit
End Function

A Demo Database with all three Function Codes, with the sample Products Table and Queries attached for Download.


  1. Running Sum in MS-Access Query
  2. Opening Access Objects from Desktop
  3. Diminishing Balance Calc in Query
  4. Auto Numbers in Query Column Version-2
  5. Word Mail-Merge With MS-Access Table
    Share:

    MS-Access and Creating Desktop Shortcuts.

    Access Desktop Shortcuts.

    The CreateShortcut() method of the Windows Script Host Object creates Desktop shortcuts directly from Microsoft Access. These shortcuts can launch frequently used files—such as Access databases, Excel workbooks, Word documents, text files, and more—right from the Desktop. This concept is familiar, but the question is: how do we implement it within Access?

    Earlier, we explored the Popup() method of the Windows Script Object to design a custom Message Box in Access that automatically closes after a specified duration. Unlike the standard Access MsgBox, which always requires a user click to proceed, our new 'MesgBox()' function provides greater flexibility. Hopefully, you’ve already tested it and started applying it in your projects.

    The VBA Shortcut() Function Prototype.

    The simple VBA Function Code that creates a Desktop Shortcut is provided below for your review. All the required parameters are given as constants in the Function for clarity.

    Public Function ShortCut()
    Dim objwshShell As Object
    Dim objShortcut As Object
    
    Set objwshShell = VBA.CreateObject("WScript.Shell")
    Set objShortcut = objwshShell.CreateShortCut("C:\Users\User\Desktop\Hello.txt.lnk")
    With objShortcut
        .TargetPath = "C:\Windows\Notepad.exe "
        .Arguments = "D:\Docs\Hello.txt"
        .WorkingDirectory = "D:\Docs"
        .Description = "Opens Hello.txt in Notepad"
        .HotKey = "Ctrl+Alt+9"
        .IconLocation = "C:\Windows\System32\Shell32.dll,130"
        .WindowStyle = 2
        .Save
    End With
    End Function
    

    You can create a Desktop Shortcut using the VBA code shown earlier, with just a few adjustments to the highlighted parameter values:

    1. Replace “User” with your own Windows username in the path.

    2. Create a simple text file (e.g., Hello.txt) containing any text and save it in one of your folders.

    3. Update the Arguments value in the code with the correct file path of your Hello.txt file.

    4. Set the Working Directory parameter to the folder the file is saved.

    5. Let the remaining parameter values stay as they are.

    As an additional feature, the HotKey combination Ctrl+Alt+9 will be assigned to the shortcut. Pressing this key sequence runs Desktop Shortcut and opens the file for editing.

    The Desktop Shortcut Icon.

    In the IconLocation parameter, notice the number 130 at the end. This number determines the icon that will appear on your Desktop Shortcut.

    The numeric range is 0 to 305, each corresponding to a different icon available in the system library.

    For example, the value 130 produces the following icon image:

    You can also change the Shortcut Icon manually at any time:

    1. Right-click on the Desktop Shortcut and select Properties from the menu.

    2. On the Shortcut tab, click the Change Icon… button.

    3. Browse through the available icons, select the preferred one, and click OK.

    4. Finally, click Apply to update the Shortcut with the new icon.

    Icon Images List.

    When you open the Change Icon window, it displays about 76 columns with 4 icons each.
    To identify the numeric index of a particular icon, start counting from the top-left icon to the right. Multiply the column count by 4, and you’ll get the approximate icon number.

    For example:

    • The first column (4 icons) corresponds to numbers 0–3.

    • The second column corresponds to 4–7.

    • The third column corresponds to 8–11, and so on.

    This manual counting method is the only reliable way I’ve found to determine the correct icon index number.
    (See the reference image below for a clearer understanding.)

    The DesktopShortcut() Function.

    We are now ready to create our VBA function that generates a desktop shortcut.
    This function requires at least three parameters, which must be supplied at call time.
    Based on these inputs, it will build a shortcut on the desktop.

    The complete VBA code for the function is given below:

    Option Compare Database
    Option Explicit
    
    
    Public Function DesktopShortCut(ByVal strShortCutName As String, _
    ByVal strProgramPath As String, _
    ByVal strFilePath As String, _
    Optional strWorkDirectory As String = "", _
    Optional ByVal strHotKey As String = "") As Boolean
    
    On Error GoTo DesktopShortCut_Err
    '-----------------------------------------------------------------
    'Function: DesktopShortCut()
    'Author: a.p.r. pillai
    'Rights: All Rights(c) Reserved by www.msaccesstips.com
    'Remarks: You may modify the Code, but need to keep these
    'Rem lines intact.
    'Parameters
    '-----------------------------------------------------------------
    '1. Shortcut Name: Shows below the Desktop Icon
    '2. strProgramPath: e.g.: "C:\Windows\System32\Notepad.exe"
    '3. strfilePath: File PathName to Open, e.g. "D:\Docs\Helloworld.txt"
    '4. Optional strWorkDirectory: e.g. "D:\Docs"
    '5. Optional strHotKey: Quick Launch - e.g. Ctl+Alt+9: 1-9,A-Z
    '-----------------------------------------------------------------
    Dim objwshShell As Object
    Dim objShortcut As Object
    Dim strPath As String
    Dim strProg As String, a As String, b As String
    Dim strTemp As String
    Dim DeskPath As String
    Dim strmsg As String
    Dim badchar As String, Flag As Boolean
    Dim j, count As Integer
    
    strPath = Environ("Path")
    
    'Validation Checks
    GoSub IsValidName
    GoSub ValidateParams
    
    'Find Current User Desktop
    strTemp = Mid(strPath, InStr(1, strPath, "C:\Users\"), 25)
    DeskPath = "C:\Users\" & Mid(strTemp, 10, InStr(10, strTemp, "\") - 10) & "\Desktop\"
    DeskPath = DeskPath & strShortCutName & ".Lnk"
    
    Set objwshShell = VBA.CreateObject("WScript.Shell")
    Set objShortcut = objwshShell.CreateShortCut(DeskPath)
    With objShortcut
    If InStr(1, Trim(strProgramPath), " ") > 0 Then
        .TargetPath = Chr(34) & Trim(strProgramPath) & Chr(34) '="C:\Windows\Notepad.exe"
    Else
        .TargetPath = Trim(strProgramPath)
    End If
    If InStr(1, Trim(strFilePath), " ") > 0 Then
        .Arguments = Chr(32) & Chr(34) & strFilePath & Chr(34) '="D:\Docs\Hello.txt"
    Else
        .Arguments = Chr(32) & strFilePath '="D:\Docs\Hello.txt"
    End If
    'Optional Working Directory
     If Len(strWorkDirectory) > 0 Then
        .WorkingDirectory = strWorkDirectory '="D:\Docs"
     End If
     'Optional Keyboard HotKey
     If Len(Nz(strHotKey, "")) > 0 Then
        .HotKey = "Ctrl+Alt+" & strHotKey '= "Ctrl+Alt+K"
     Else
        .HotKey = ""
     End If
        .IconLocation = "C:\Windows\System32\Shell32.dll,130" '0 - 305
        .WindowStyle = 2
        .Save
    End With
    DesktopShortCut = True
    
    DesktopShortCut_Exit:
    Exit Function
    
    IsValidName:
    Flag = True
    badchar = "\/:*?" & Chr(34) & "<>|"
    count = 0
    For j = 1 To Len(strShortCutName)
        If InStr(1, badchar, Mid(strShortCutName, j, 1)) Then
            count = count + 1
        End If
    Next
    Flag = IIf(count, False, True)
    If Not Flag Then
        MsgBox "Shortcut Name: " & strShortCutName & vbCr & vbCr _
        & "Contains Invalid Characters." & vbCr & vbCr _
        & "*** Program Aborted. ***", , "DeskShortCut()"
        
        DesktopShortCut = False
        Exit Function
    End If
    Return
    
    ValidateParams:
    strmsg = ""
    'Program Path
    If Len(Nz(strProgramPath, "")) > 0 Then
       'Check whether the Program exists in the given path
       If InStr(1, strProgramPath, Dir(strProgramPath)) = 0 Then
         strmsg = "Program Path: " & strProgramPath & " Invalid."
       End If
    Else
       strmsg = "Program Path: Not found!"
    End If
    'File Path
    If Len(Nz(strFilePath, "")) > 0 Then
       If InStr(1, strFilePath, Dir(strFilePath)) = 0 Then
         If Len(strmsg) > 0 Then
            strmsg = strmsg & vbCr & "File Path: " & strFilePath & " Invalid."
         Else
            strmsg = "File Path: " & strFilePath & " Invalid."
         End If
       End If
    Else
        If Len(strmsg) > 0 Then
            strmsg = strmsg & vbCr & "File Path: Not found!"
        Else
            strmsg = "File Path: Not found!"
        End If
    End If
    If Len(strmsg) > 0 Then
        MsgBox strmsg, , "DeskShortCut()"
        DesktopShortCut = False
        Exit Function
    End If
    Return
    
    DesktopShortCut_Err:
    MsgBox Err & " : " & Err.Description, , "DesktopShortCut()"
    DesktopShortCut = False
    Resume DesktopShortCut_Exit
    End Function

    The DesktopShortcut() function is defined with five parameters, of which the last two—Working Directory and HotKey—are optional.

    To ensure reliability, validation checks have been included for the parameter values, along with error-trapping routines. These safeguard the function from unexpected issues and allow it to exit gracefully without crashing. Demo Run of the DesktopShortcut() Function.

    The sample Run of the Function from the Immediate Window is given below:

    Sample Run-1.

    DesktopShortcut "HelloMyDB","C:\Program Files (x86)\Microsoft Office\Office12\MSACCESS.EXE","D:\New Folder\ClassDB.accdb"

    Sample Run-2.

    DesktopShortcut "HelloMyDoc","C:\Program Files (x86)\Microsoft Office\Office12\WINWORD.EXE","D:\Docs\TelNo2411808.docx","D:\Docs","T"


    The TreeView Control Tutorial Session Links.

    1. Microsoft TreeView Control Tutorial
    2. Creating an Access Menu with a TreeView Control
    3. Assigning Images to TreeView Control
    4. Assigning Images to TreeView Control-2
    5. TreeView Control Check-Mark Add Delete Nodes
    6. TreeView ImageCombo Drop-Down Access Menu
    7. Re-arrange TreeView Nodes by Drag and Drop
    8. ListView Control with MS-Access TreeView
    9. ListView Control Drag-and-Drop Events
    10. TreeView Control With Subforms
    Share:

    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