我有一个用户窗体,其中包含5列的列表框。当您单击搜索按钮时,我希望使用SQL表中的搜索结果填充列表框。
使用rs时,我不断收到“类型声明字符与声明的数据类型不匹配”的提示!适用于.RowSource。
Sub searchall()
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim list As Object
Set list = SearchForm.Results
Server_Name = "SDL02-VM25"
Database_Name = "PIA"
SQLStr = "select [Agentname],[position],[employeegroup],[supervisor],[manager] from dbo.[HistoricalMasterStaffing] Where [FirstName] ='" & SearchForm.firstname.value & "' or [LastName] ='" & SearchForm.lastname.value & "' or [Date] = '" & SearchForm.DateSearch.value & "' or [year] = '" & SearchForm.Year.value & "' or [employeegroup] = '" & SearchForm.EmployGroup.value & "' or [position] = '" & SearchForm.Position.value & "' or [ftpt] = '" & SearchForm.PTFT.value & "' or [Contractagency] = '" & SearchForm.Agency.value & "' or [termcode] = '" & SearchForm.TermCode.value & "' or [location] = '" & SearchForm.Location.value & "'"
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & vbNullString
rs.Open SQLStr, Cn, adOpenStatic
With list
.Top = 252
.Left = 36
.Width = 573
.Height = 188.3
.ColumnHeads = True
.ColumnCount = 5
.ColumnWidths = "100;100;100;100;100;"
.MultiSelect = fmMultiSelectExtended
.RowSource = rs!
End With
rs.Close
Cn.Close
Set rs = Nothing
Set Cn = Nothing
End Sub
答案 0 :(得分:1)
您可以在数组中获取记录集,然后像这样填充ListBox。而且由于您是动态填充ListBox的,因此Headers在这里不起作用,但是您可以在ListBox上方添加带有标题的Labels。
Dim arr
arr = rs.GetRows
.List = arr
答案 1 :(得分:0)
这是我从工作表加载多个列列表框的方式。我确定可以使用数组完成此操作,但是您需要5个数组或一个多维数组。
With Me.ListBox2
.Clear 'clear to set up the list
.ColumnCount = 4
.ColumnWidths = "60;70;65;150"
For i = 0 To LastRow - 2 'data starts in Row2
If LastRow >= 2 Then
.AddItem
.List(i, 0) = DATAsheet.Cells(i + 2, 1) 'Column of the ID, data starts in row 2
.List(i, 1) = DATAsheet.Cells(i + 2, 4) 'Column of the Date, data starts in row 2
.List(i, 2) = DATAsheet.Cells(i + 2, 2) ' Column of motor Size, data starts in row 2
.List(i, 3) = DATAsheet.Cells(i + 2, 3) ' Column of motor SN, data starts in row 2
Else ' Do nothing
End If
Next i
End With