我从 Excel VBA 中解决了这个问题,查询 Access 2007 X.accdb 文件:
'
' Variables:
' i: counter
' j: counter
' nFlds: number of fields in the query
' nMax: maximum number of records to be exported, 0=no limit
' strQry: query name
'
' objApp: Access.Application
' qdf: QueryDef
' rst: Recordset
'
Function daoDoQuery()
'
Dim i, j, nFlds, nMax, strQry
'
Dim objApp, qdf
Dim rst As DAO.Recordset
'
Set objApp = CreateObject("Access.Application")
objApp.OpenCurrentDatabase "some_path\AllInformation.accdb"
'
' get Recordset:
'
strQry = "MyQuery"
Set qdf = objApp.CurrentDb.QueryDefs(strQry)
'
' here [Current date] is entered:
'
qdf.Parameters(0).Value = Now()
Set rst = qdf.OpenRecordset(dbOpenDynaset)
'
If (rst.EOF) Then
Set rst = Nothing
daoDoQuery = 0
Exit Function
End If
'
nFlds = rst.Fields.Count
'
' create a new Excel Workbook to write results:
'
i = 1
Application.ScreenUpdating = False
Workbooks.Add
For j = 1 To nFlds
With Cells(i, j)
.Font.Bold = True
.Font.Size = 12
.Value = rst.Fields(j - 1).Name
End With
Next
'
nMax = 50
i = i + 1
'
Do While (Not rst.EOF)
'
For j = 1 To nFlds
Cells(i, j).Value = rst(j - 1)
Next
'
rst.MoveNext
i = i + 1
If (nMax > 0) Then
If (i > nMax) Then
Exit Do
End If
End If
Loop
'
Application.ScreenUpdating = True
'
rst.Close
Set rst = Nothing
Set qdf = Nothing
Set objApp = Nothing
'
daoDoQuery = 1
'
End Function
这将完成这项工作,我将创建一个新的 Excel 工作簿,其中第一个工作表作为结果列表:
daoDoQuery