In this example I will show how we can populate a combobox in a userform with data from a database.
What we need:
* MS Windows 2000 or above
* MS Excel 2000 or above
* MDAC 2.5 or above (ADO Library)
Step 1
Add a reference to MS ADO Library x.x via Tools | Reference... in the VB-Editor.
Step 2
Insert following code in a standardmodule:
VB:
Option Explicit
Sub Populate_Combobox_Recordset()
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim stDB As String, stConn As String, stSQL As String
Dim xlCalc As XlCalculation
Dim vaData As Variant
Dim k As Long
With Application
xlCalc = .Calculation
.Calculation = xlCalculationManual
.EnableEvents = False
.ScreenUpdating = False
End With
Set cnt = New ADODB.Connection
stDB = ThisWorkbook.Path & "\" & "Test.mdb"
stConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & stDB & ";"
stSQL = "SELECT * FROM tblData"
With cnt
.CursorLocation = adUseClient
.Open stConn
Set rst = .Execute(stSQL)
End With
With rst
Set .ActiveConnection = Nothing
k = .Fields.Count
vaData = .GetRows
End With
cnt.Close
With frmData
With .ComboBox1
.Clear
.BoundColumn = k
.List = Application.Transpose(vaData)
.ListIndex = -1
End With
.Show vbModeless
End With
With Application
.Calculation = xlCalc
.EnableEvents = True
.ScreenUpdating = True
End With
Set rst = Nothing
Set cnt = Nothing
End Sub
The most notable thing is that we need to transpose the horizontal array vaData to an vertical to add it to the combobox.
Happy dataretrieving
Bookmarks