简体   繁体   中英

excel vba to populate combobox in worksheet from sql select query

I have a good connection in Excel to the sqlDb (in a Module - public function).

I have used this connection with a simple Select query (in Sheet1 code) which works nicely. Per below code:

Private Sub Selection()

Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")

Dim sqlstr As String
sqlstr = "Select * from Selection"

Call connectDatabase
rs.Open sqlstr, DBCONT

If rs.RecordCount > 0 Then
    For i = 1 To rs.RecordCount
          With ThisWorkbook.Sheets("Sheet1")
            .Cells(i, 1).Value = rs(0)
            .Cells(i, 2).Value = rs(1)
          End With
          rs.movenext
     Next i
 Else
    MsgBox "FFS"

 End If
 rs.Close
 Set rs = Nothing
 Call closeDatabase

 End Sub

Now rather than output these results into cells (1,1) and (1,2) of Sheet1, I want above results to populate my Combobox1 on Sheet1 and do away with the output. I have looked at a lot of solutions but I am struggling.

Grateful if you can help or direct me to the best answer.

Thank you.

Dasal

Private Sub Selection()

Dim rs As Object

Set rs = CreateObject("ADODB.Recordset")

Dim sqlstr As String
sqlstr = "Select * from Selection"

Call connectDatabase
rs.Open sqlstr, DBCONT

ComboBox1.Clear
If rs.RecordCount > 0 Then
    For i = 1 To rs.RecordCount

        ComboBox1.AddItem rs(1)
          rs.movenext
     Next i
 Else
    MsgBox "FFS"

 End If
 rs.Close
 Set rs = Nothing
 Call closeDatabase

 End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM