【发布时间】: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