MS Access VBA导出查询结果

时间:2009-09-18 20:13:36

标签: ms-access vba export

我需要帮助提出一种方法,允许用户在按钮点击事件中将查询结果导出到xls文件。 我尝试使用输出到宏,但它不适用于包含30,000多条记录的查询。

提前致谢

2 个答案:

答案 0 :(得分:4)

您可能需要考虑使用自动化来创建Excel电子表格并自行填充它而不是使用宏。

这是我过去用来做的一个功能。

Public Function ExportToExcel(FileToCreate As String, ByRef rst As ADODB.Recordset)
'Parms:     FileToCreate - Full path and file name to Excel spreadsheet to create
'           rst - Populated ADO recordset to export

On Error GoTo Err_Handler

Dim objExcel As Object
Dim objBook As Object
Dim objSheet As Object

'Create a new excel workbook; use late binding to prevent issues with different versions of Excel being
'installed on dev machine vs user machine
Set objExcel = CreateObject("Excel.Application")
Set objBook = objExcel.Workbooks.Add

'Hide the workbook temporarily from the user
objExcel.Visible = False

objBook.SaveAs (FileToCreate)

'Remove Worksheets so we're left with just one in the Workbook for starters
Do Until objBook.Worksheets.Count = 1
   Set objSheet = objBook.Worksheets(objBook.Worksheets.Count - 1)
   objSheet.Delete
Loop

Set objSheet = objBook.Worksheets(1)

rst.MoveFirst

'Use CopyFromRecordset method as this is faster than writing data one row at a time
objSheet.Range("A1").CopyFromRecordset rst

'The UsedRange.Rows.Count property can be used to identify the last row of actual data in the spreadsheet
'This is sometimes useful if you need to add a summary row or otherwise manipulate the data
'Dim lngUsedRange As Long
'lngUsedRange = objSheet.UsedRange.Rows.Count

'Save the spreadsheet
objBook.Save

objExcel.Visible = True

ExportToExcel = True

Err_Handler:
   Set objSheet = Nothing
   Set objBook = Nothing
   Set objExcel = Nothing
   DoCmd.Hourglass False

   If Err.Number <> 0 Then
      Err.Raise Err.Number, Err.Source, Err.Description
   End If
End Function

答案 1 :(得分:1)

你能使用VBA吗?

Intellisense会帮助您,但请开始使用:

DoCmd.TransferSpreadsheet acExport,acSpreadsheetTypeExcel9,“my_query_name”,“C:\ myfilename.xls”

注意:您可能有不同的Excel版本 “my_query_name”是查询或表的名称 您需要将文件位置设置为适当的位置\ name .extension

更多信息:http://msdn.microsoft.com/en-us/library/bb214134.aspx

相关问题