我要做的就是使用 VBA 将某些查询的结果放入 Excel 工作簿中。主要问题是 openRecordSet 方法似乎不起作用。每次我尝试调试它时,我都会看到记录集(rcset)什么都没有。当我只是运行查询以便在 Access 查看器中查看它时,它似乎工作得很好(见最后一行代码)。运行代码时我没有收到任何错误,所以我很难理解为什么我的记录集会返回 Nothing。我在互联网上搜索了很多,但没有找到任何处于这种特殊情况的人。提前感谢您的帮助!
Dim db As DAO.Database
Dim qdef As DAO.QueryDef
Dim rcset As DAO.Recordset
Dim i As Integer
'Identify the database and query
Set db = CurrentDb
On Error Resume Next
With db
.QueryDefs.Delete ("RealQuery")
Set qdef = .CreateQueryDef("RealQuery", strSQLRQ)
.Close
End With
'The problem child line
Set rcset = qdef.OpenRecordset()
'Clear previous contents
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.Workbooks.Add
.Sheets("Sheet1").Select
'Copy the recordset to Excel
.ActiveSheet.Range("A2").CopyFromRecordset rcset
'Add column heading names to spreadsheet
For i = 1 To rcset.Fields.Count
xlApp.ActiveSheet.Cells(1, i).Value = MyRecordset.Fields(i - 1).Name
Next i
xlApp.Cells.EntireColumn.AutoFit
End With
qdef.Close
Set qdef = Nothing
Set db = Nothing
DoCmd.OpenQuery "RealQuery", acViewNormal