2009-09-18 147 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