我编写了以下代码来将数据从Access表导入Excel,但我在rs.MoveFirst
读取时收到错误消息:
EOF或BOF为真,或当前记录已被删除
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim ws As Excel.Application
Dim strSQL As String
Dim i As Long
strSQL = "SELECT * FROM salebill where date >= " & _
sale.fromdate.Value & " And date <= " & sale.todate.Value & ""
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\Payroll Soft\Acess\Mobile Shop.mdb;"
.Open
End With
Set rs = New ADODB.Recordset
rs.Open strSQL, cn, adOpenKeyset, adLockOptimistic, adCmdTableDirect
rs.MoveFirst
MsgBox (rs.RecordCount & " Rows Generated")
''Code to Export Data to Export''
Set ws = CreateObject("Excel.Application")
ws.Workbooks.Add
ws.range("a3").Select
ws.Selection.NumberFormat = "0"
For i = 0 To rs.Fields.Count - 1
ws.ActiveCell.Offset(0, i).Value = rs.Fields(i).Name
Next
ws.range("a4").Select
Do Until rs.EOF
For i = 0 To`enter code here` rs.Fields.Count - 1
ws.ActiveCell.Offset(0, i).Value = rs.Fields(i).Value
Next
ws.ActiveCell.Offset(1, 0).Select
rs.MoveNext`enter code here`
Loop
rs.Close
答案 0 :(得分:0)
在尝试使用记录集之前,您需要测试EOF
。
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim ws As Excel.Application
Dim strSQL As String
Dim i As Long
strSQL = "SELECT * FROM salebill where date Between #" & _
sale.fromdate.Value & "# And #" & sale.todate.Value & "#"
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\Payroll Soft\Acess\Mobile Shop.mdb;"
.Open
End With
Set rs = New ADODB.Recordset
rs.Open strSQL, cn, adOpenKeyset, adLockOptimistic, adCmdTableDirect
If Not rs.EOF Then
rs.MoveFirst
MsgBox (rs.RecordCount & " Rows Generated")
''Code to Export Data to Export''
Set ws = CreateObject("Excel.Application")
ws.Workbooks.Add
ws.range("a3").Select
ws.Selection.NumberFormat = "0"
For i = 0 To rs.Fields.Count - 1
ws.ActiveCell.Offset(0, i).Value = rs.Fields(i).Name
Next
ws.range("a4").Select
Do Until rs.EOF
For i = 0 To rs.Fields.Count - 1
ws.ActiveCell.Offset(0, i).Value = rs.Fields(i).Value
Next
ws.ActiveCell.Offset(1, 0).Select
rs.MoveNext
Loop
If (rs.State And adStateOpen) = adStateOpen Then rs.Close
Set rs = Nothing
End If
If (cn.State And adStateOpen) = adStateOpen Then cn.Close
Set cn= Nothing