Question : How to Populate a ListBox Control with Values from an Access Database Table

I have ListBox1 Control on a VBA Form1.
I need help with code for the initialise event of Form1 which will populate this ListBox1 with Values (in alphabetical order) from the PName field of all records in a table (named ClientNames) in an Access database.
The name and location of my Access Database that contains the table ClientNames are as follows:
C:\My Folder\MyDatabase.mdb
Many thanks for your help.
Please note I am using Visual Basic For Applications for a Project in Microsoft Word

Answer : How to Populate a ListBox Control with Values from an Access Database Table

I think that you need something like this.  Remember to set a reference to the Microsoft Active Data Objects library.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
Private Sub UserForm_Initialize()
    Dim cn As New ADODB.Connection
    Dim rs As New ADODB.RecordSet
    Dim strConn As String
    
    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\My Folder\MyDatabase.mdb;User Id=admin;Password=;"
    cn.Open strConn
        rs.Open "Select * From ClientNames ORDER By Pname", cn, adOpenDynamic, adLockOptimistic, adCmdText
            ListBox1.Clear
            Do Until rs.EOF
                ListBox1.AddItem rs, rs.Fields("PName").Value
                rs.MoveNext
            Loop
        rs.Close
    cn.Close

End Sub
Random Solutions  
 
programming4us programming4us