我有一个包含宏的 Excel 2010 模板文件,其中包含以下代码:
ActiveWorkbook.SaveAs Filename:= _
newname, FileFormat:= _
51, CreateBackup:=False
这会将当前工作簿保存为非启用宏的工作簿,但我显然无法运行我需要的其余宏。
我尝试过使用
ActiveWorkbook.SaveCopyAs Filename:= _
newname, FileFormat:= _
51, CreateBackup:=False
这会产生语法错误。我的目标是使用新名称保存副本,因此模板文件保持不变并且可以每天运行。
试试这个:
Dim wMacro As Workbook 'workbook you want to save
wMacro.Sheets(Array("Sheet1", "Sheet2", "etc")).Select
wMacro.Sheets(Array("Sheet1", "Sheet2", "etc")).Copy
ActiveWorkbook.SaveAs Filename:= "filename.xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
它将创建一个副本并保存。
接受的答案将引发错误,因为未设置 new_Workbooks 对象,此处未更新和修改代码:
Sub Workbook_Copy_and_Save()
Dim new_Workbooks As Workbook
' Create a new workbook
Set new_Workbooks = Workbooks.Add
' Copy the specified sheets to the new workbook
ThisWorkbook.Sheets(Array("SheetA", "SheetB", "etc")).Copy Before:=new_Workbooks.Sheets(1)
' Optional disable alerts of next action
Application.DisplayAlerts = False
' Optional delete Excel default Sheet1 in the new file
new_Workbooks.Sheets("Sheet1").Delete
' Save the copy in the same directory of the origina file, named as newFileName.xlsx
new_Workbooks.SaveAs filename:=ThisWorkbook.path & "\" & "newFileName.xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
' Optional close the new file created
new_Workbooks.Close
' Optional re-enable alerts if more code needs to be run
Application.DisplayAlerts = True
End Sub