下面是我使用ADO Recordset设置ListBox的代码。它工作正常但不应该以表格形式显示。
Function PopulatelstReview()
Dim sList As String
Dim i As Long
Dim ADORs As ADODB.Recordset
Dim strSearchResult As String
Set AdoCn = New ADODB.Connection
Set AdoCmd = New ADODB.Command
AdoCn.Open AdoConnectionString
AdoCmd.ActiveConnection = AdoConnectionString
Debug.Print AdoConnectionString
Set ADORs = New ADODB.Recordset
'rs.Open "TestListReview", AdoCn
ADORs.CursorLocation = adUseClient
'rs.Open strSQL, AdoConnectionString, adOpenDynamic, adLockOptimistic, adCmdText
AdoCmd.CommandType = adCmdStoredProc
AdoCmd.CommandText = "TestListReview"
Set rs = AdoCmd.Execute
Set ADORs = ExecuteStoredProcedure("TestListReview", AdoCmd)
With ADORs
lstReview.RowSourceType = "Value List"
lstReview.ColumnHeads = False
Label43.Caption = ADORs.Fields(0).Name
Label44.Caption = ADORs.Fields(1).Name
Label45.Caption = ADORs.Fields(2).Name
Label48.Caption = ADORs.Fields(3).Name
Label49.Caption = ADORs.Fields(4).Name
Label50.Caption = ADORs.Fields(5).Name
Label51.Caption = ADORs.Fields(6).Name
Label52.Caption = ADORs.Fields(7).Name
lstReview.AddItem ADORs!id
lstReview.AddItem ADORs!TradePartner
lstReview.AddItem ADORs!TrustAccount
lstReview.AddItem ADORs!Date
lstReview.AddItem ADORs!CurrentBalance
lstReview.AddItem ADORs!FileName
lstReview.AddItem ADORs!RecordNum
lstReview.AddItem ADORs!ImportDateTime
sList = ADORs.GetString(adClipString, , ";", ";")
'lstReview.RowSourceType = "Value List"
'lstReview.RowSource = sList
End With
'Call RS2WS(ADORs, "A3")
'lstReview.Column(0, 1) = "ID"
End Function
我需要每个值都应该放在我放在标签中的合适列中。请告诉我该怎么做
答案 0 :(得分:2)
您使用的是Excel还是Access? 如果您使用Access,则可以导入/链接表并使用普通查询作为(recordsource)来填充列表框。
无论如何,这是一个伪代码,用于使用您的方法填充列表框。连接到服务器并执行SQL语句后,请尝试以下代码。
Dim RC, CC As Long
ADORs.MoveLast ' vba will not know the total row until you scroll down to the last
RC = ADORs.RecordCount ' get the result row count
CC = ADORs.Fields.count ' get the field/column count
ADORs.MoveFirst ' Move back to the first record
lstReview.ColumnHeads = True
lstReview.ColumnCount = CC ' Number of column as in the recordset
'Fill the column names
Dim I As Integer
For I = 0 To CC - 1
lstReview.Column(I, 0).value = ADORs.Fields(I).name
Next I
'Fill the data
Dim J As Integer
While Not ADORs.EOF
For I = 1 To RC - 1
For J = 0 To CC - 1
lstReview.Column(J, I).value = ADORs.Fields(J).value
Next J
Next I
ADORs.MoveNext 'moving to next record
Wend
此外,您应该考虑捕获错误,例如SQL执行是否已返回任何记录。
要访问,您可以使用此
If Nz(ADORs.RecordCount, 0) = 0 Then
MsgBox "Sorry no records found.."
Exit Sub
End If
如果你使用excel,你可以使用类似的东西
If isNull(ADORs.RecordCount) or (ADORs.RecordCount = 0) Then
MsgBox "Sorry no records found.."
Exit Sub
End If
希望这有助于..享受:)