2009-09-18 146 views
0

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

在此先感谢

+0

你可以发布你的代码吗? (在我的回答中,你表示你试过docmd。) – JeffO 2009-09-18 21:03:39

+0

什么是Excel的目标版本?行数的限制毫无疑问是Excel的限制,而不是Access的限制。 Excel 2007增加了行数,顺便说一句。 – 2009-09-20 02:52:28

+1

事实上,托尼,我认为Access 2002标签在这里是有用的信息,因为它限制了导出格式。当然,我认为应该使用标签的方式是只应使用MS-ACCESS,并在问题中指出特定版本,但是您删除了标签但未将版本添加到问题文本中。在我看来,这会丢失有用的信息。 – 2010-09-11 19:41:16

回答

1

您可以使用VBA吗?

智能感知会帮助你,但上手:

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

注意:您可以有不同的Excel版本 “my_query_name”是你的查询或表 你需要设置文件位置的适当位置\名称的名称。扩展名

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

+0

我试过了,但我一直收到一个文件不存在在该位置错误。 – zSynopsis 2009-09-18 20:43:38

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 
+0

这段代码适合我,但唯一的问题是,Excel数据没有标题..我怎么能添加它? – 2016-04-12 07:18:12