保存单个Excel工作表作为新的Excel文件与新的input

我正在与VBA和访问2010年。我在这里有一个Excel文件作为模板,3个不同的工作表,我想写这些不同的工作表中的东西取决于什么是在我的访问分贝。 我只是有一个麻烦:原来的Excel模板文件不应该改变。 我想保存在一个新的文件与我的input,这次只有1工作表(取决于访问数据库中的什么)。

所以这是我的代码访问:

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

但是,如何? 有任何想法吗? 谢谢

下面的代码将您的工作簿保存在一个新的位置,只有一个工作表包含您的输出。

 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