excel vba从sql select查询中填充工作表中的组合框

时间:2017-09-11 13:45:28

标签: sql excel vba select combobox

我在Excel中与sqlDb(在模块 - 公共函数中)有良好的连接。

我使用了一个简单的Select查询(在Sheet1代码中)这个连接很好用。以下代码:

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

现在不是将这些结果输出到Sheet1的单元格(1,1)和(1,2)中,我希望上面的结果填充Sheet1上的Combobox1 并取消输出。我看了很多解决方案,但我很挣扎。

感谢您能帮助或指导我找到最佳答案。

谢谢。

Dasal

1 个答案:

答案 0 :(得分:0)

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