我正在使用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
怎麼會呢?有任何想法嗎?謝謝
用'excelObject.SaveAs 「new_file_path」' –