使用查询数据填充Excel用户表单列表框 - 列表框为空

时间:2015-06-18 18:13:30

标签: sql sql-server excel vba listbox

我正在尝试将excel文档中userform的列表框从查询填充到SQL Server,但列表框始终为空。

我正在尝试获取要填充的位置列表,我将用它来定义后续查询的参数。

这是我的代码:

Option Explicit
Sub Populate_ListBox_From_SQL()
    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

    'set SQL connection and connection string
    Set cnt = New ADODB.Connection

    stConn = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DW;Data Source=use-rptdw-00;Use Procedure for Prepare=1;Auto Translate=True;" _
    & "Packet Size=4096;Workstation ID=PI-L-C03RTRD;Use Encryption for Data=False;Tag with column collation when possible=False"

    cnt.ConnectionString = stConn

    'your SQL statement
    stSQL = "SELECT ldesc FROM fin.location ORDER BY ldesc"

    With cnt
        .CursorLocation = adUseClient 'Necesary for creating disconnected recordset.
        .Open stConn 'Open connection.
        'Instantiate the Recordsetobject and execute the SQL-state.
        Set rst = .Execute(stSQL)
    End With

    With rst
        Set .ActiveConnection = Nothing 'Disconnect the recordset.
        k = .Fields.Count
         'Populate the array with the whole recordset.
        vaData = .GetRows
    End With

     'Close the connection.
    cnt.Close

     'Manipulate the Listbox's properties and show the form.
     With UserForm1
        With .ComboBox1
            .Clear
            .BoundColumn = k
            .List = Application.Transpose(vaData)
            .ListIndex = -1
        End With
        .Show vbModeless
    End With

    'Release objects from memory.
    Set rst = Nothing
    Set cnt = Nothing
End Sub

也许我把代码放在错误的地方?我在userform的基础VBA代码下拥有它。 或者我可能需要为ListBox本身设置属性?

我对VBA很新,所以任何帮助都会受到赞赏

1 个答案:

答案 0 :(得分:0)

没关系。我想到了。我只是没有明确调用该函数。虽然,现在我得到“运行时错误'400':表格已经显示;无法显示模态”错误。

知道如何阻止这种情况发生吗?

相关问题