Populate ListBox from SQL table

JagsBrian

New Member
Joined
Jan 16, 2018
Messages
2
Here is my code so far:

Code:
Private Sub UserForm_Initialize()
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim i As Integer
cnn.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Forecast;Data Source=sqlaxrpt;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=BRIANBECK-LT;Use Encryption for Data=False;Tag with column collation when possible=False"
rst.Open "SELECT [PurchID], [ITEMID], [INVENTSITEID], [REMAINPURCHPHYSICAL], [DELIVERYDATE] FROM PurchasingTable WHERE ItemID = 'K3930903';", cnn, adOpenStatic ', adLockUnspecified
rst.MoveFirst
i = 0
    With Me.ListBox1
    .ColumnCount = 5
    .ColumnWidths = "50;50;50;50;50"
    .Clear
        Do
        .AddItem
        .List(i, 0) = rst![PurchID]
        .List(i, 1) = rst![ItemID]
        .List(i, 2) = rst![INVENTSITEID]
        .List(i, 3) = rst![REMAINPURCHPHYSICAL]
        .List(i, 4) = rst![DELIVERYDATE]
        i = i + 1
        rst.MoveNext
        Loop Until rst.EOF
    End With
End Sub

I am getting an error at .List(I,0) = rst![PurchID] (Run-time error '424' Object Required)

Any ideas what I'm doing wrong?
 

Excel Facts

Can a formula spear through sheets?
Use =SUM(January:December!E7) to sum E7 on all of the sheets from January through December
I noticed that when I set the code to Option Explicit, it says that I have a Compile Error: Variable not defined (on the same line that I am getting the error before)
 
Upvote 0
Does this work?
Code:
        .List(i, 0) = rst.Fields("PurchID").Value
PS You could use GetRows to put the data from the recordset into an array and then use that array to populate the listbox directly without having to loop.
 
Upvote 0

Forum statistics

Threads
1,214,832
Messages
6,121,841
Members
449,051
Latest member
excelquestion515

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top