【问题标题】:Populate Excel userform listbox with query data - listbox is blank使用查询数据填充 Excel 用户表单列表框 - 列表框为空白
【发布时间】:2015-06-18 18:13:30
【问题描述】:

我正在尝试从查询到 SQL Server 的 Excel 文档中的用户窗体上填充列表框,但列表框始终为空白。

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

这是我的代码:

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

也许我把代码放在了错误的地方?我在用户窗体的基本 VBA 代码下有它。 或者也许我需要为 ListBox 本身设置属性?

我对 VBA 还很陌生,因此我们将不胜感激

【问题讨论】:

    标签: sql sql-server excel vba listbox


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 2018-05-11
      • 2021-02-13
      • 2011-11-07
      • 1970-01-01
      • 2019-11-02
      相关资源
      最近更新 更多