Load a combo box using ADODB

By | 2019-10-04

Although this code could tightened up a bit, it demonstrates how to load a combo box with data from an Access database, via an ADODB connection.

Place on a form a combo box and a command button

Public Const strJetProvider = "Provider=Microsoft.Jet.OLEDB.3.51;DataSource=C:\myaccess.mdb"
Public sub Command1_Click()

    Dim MyConn As New ADODB.Connection
    Dim MyRst As New ADODB.Recordset
    Dim strTemp As String


    With MyConn
        .ConnectionString = strJetProvider
        .Open
    End With
    With Me
        .Combo1.Clear
    End With
    MyRst.Open "SELECT * FROM SQL", MyConn, adLockReadOnly, adLockOptimistic, adCmdText

    If MyRst.RecordCount <= 0 Then
        MyRst.Close
        MyConn.Close
        Set MyRst = Nothing
        Set MyConn = Nothing
        strTemp = MsgBox("Sorry No Records are located?", vbOKOnly + vbCritical, "No Records Found")
        Exit Sub
    End If
    Do While Not MyRst.EOF
        If Not IsNull(MyRst("Field")) Then
            Combo1.AddItem MyRst("Field")
        End If
        MyRst.MoveNext
    Loop
    MyRst.Close
    If Combo1.ListCount > 0 Then
        Combo1.ListIndex = 0
    End If

End Sub

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.