2014-04-27 67 views
0

我正在使用vba和訪問2010.我在這裏有一個excel文件作爲模板,有3個不同的工作表,我想在這些不同的工作表中寫東西取決於在什麼是我的訪問分貝。我只有一個麻煩:原始的Excel模板文件不應該改變。我想用我的輸入始終保存在一個新的文件中,這次只需要一個工作表(取決於訪問數據庫中的內容)。保存單個Excel工作表作爲新的excel文件與新的輸入

所以這是我在訪問代碼:

Dim excelObject As Object 
Dim sheet As Object 
Dim myRec As DAO.Recordset 
Dim fldCustName As DAO.Field 

'open excel file 
Set objExcel = CreateObject("Excel.Application") 
Set excelObject = objExcel.Workbooks.Open("MyTemplate.xlsx") 
Set sheet = excelObject.Worksheets(1) 

'read table 
Set myRec = CurrentDb.OpenRecordset("MyTable") 
Set fldCustName = myRec.Fields("ID") 

'select worksheet and add text to excel depends on table 
If fldCustName = 1000 Then 
    sheet.Cells(1, "A") = "Loop..." 
End If 
If fldCustName = 2000 Then 
    sheet.Cells(1, "A") = "Loop..." 
End If 
'and so on... 

'save and close 
excelObject.Save 'problem: writes always in the same file and only worksheet 1 
excelObject.Close 
objExcel.Quit 

正如我所說的,問題是,我一直保存更改我的template.xlsx,我也忽略了其他工作表。解決這個問題的最簡單方法是什麼?也許:

reading the table -> decide which worksheet I need -> save this worksheet as .xlsx -> start writing

怎麼會呢?有任何想法嗎?謝謝

+2

用'excelObject.SaveAs 「new_file_path」' –

回答

2

下面的代碼將您的工作簿保存在一個只包含輸出的工作表的新位置。

Excel.Application.DisplayAlerts=False 'suppresses dialog boxes when deleting worksheets 
Dim wsName As String 

'replace this code with a function that gives you the name of the worksheet 
wsName = "1" 

'add your code to query the data and write to worksheet here 

For Each Sh In excelObject.Worksheets 
    If Sh.Name <> wsName Then 
     Sh.Delete 
    End If 
Next Sh 

ThisWorkbook.SaveAs ThisWorkbook.Path & "\" & wsName & "output.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled 
Excel.Application.DisplayAlerts=True 
excelObject.Close 
+0

HEJ感謝取代'excelObject.Save',that's不錯。只是在Sh.Delete遇到一些問題 - 看起來像刪除僅在表單爲空時才起作用。如果工作表內已經存在代碼,則不會刪除該工作表。有沒有解決方法? – silla

+1

嗨,新浪,我剛剛檢查,我實際上能夠使用Sh.Delete刪除內容的工作表。你能否解釋一下當你試圖刪除一個包含內容的工作表時會發生什麼?你收到一條錯誤消息嗎? –

+0

我沒有看到任何錯誤消息,實際上根本沒有消息。嘗試不同的Excel文件,但它總是相同的:我沒有觸摸的表被刪除其他一些輸入不被刪除。想'Sh.Cells.Clear'可以幫助(這將清除工作表,所以我可能能夠刪除),但這並沒有幫助(工作表現在是空的,但仍然無法刪除)。任何想法如何調試或查看代碼背後發生了什麼? – silla

相關問題