我要执行以下操作-
Sub SaveCopy()
Set xls = CreateObject("Excel.Application")
'xls.DisplayAlerts = False
'Application.DisplayAlerts = False
Dim CurrentFile As String
CurrentFile = ThisWorkbook.FullName
ThisWorkbook.SaveAs Filename:=Replace(ThisWorkbook.FullName, "xlsm", "xls"), FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Sheets("Settings").Delete
ActiveWorkbook.Close SaveChanges:=True
Application.Workbooks.Open Filename:=CurrentFile
xls.DisplayAlerts = True
Application.DisplayAlerts = True
End Sub
此代码存在以下问题:
Application.Workbooks.Open
行未执行)我该如何解决?
答案 0 :(得分:0)
您可以执行以下操作:
Sub SaveCopy()
Dim CurrentFile As String
CurrentFile = ThisWorkbook.FullName
ThisWorkbook.SaveAs Filename:=Replace(ThisWorkbook.FullName, "xlsm", "xlsx"), FileFormat:=xlOpenXMLWorkbook
ThisWorkbook.Sheets("Settings").Delete
Application.Workbooks.Open Filename:=CurrentFile 're-open original file
ThisWorkbook.Close SaveChanges:=True
'The line above will terminate this macro immediately
'Everything beyond this line will not execute.
End Sub
请注意,如果工作簿CurrentFile
有一个Workbook_Open
事件,则该事件也会在ThisWorkbook.Close
运行时立即终止。
一种更节省的选择是使用Workbook.SaveCopyAs method。
.SaveCopyAs
无法更改文件类型,因为它不支持参数FileFormat:=
。这意味着您必须先以相同的文件格式保存副本,然后打开该副本并使用.SaveAs
重新保存以更改文件格式,然后删除临时副本。
Sub SaveCopyAdvanced()
Dim CurrentFile As String
CurrentFile = ThisWorkbook.FullName
Dim CopyFileName As String
CopyFileName = Replace(ThisWorkbook.FullName, ".xlsm", "_COPY.xlsm")
'save a temporary copy but keep the original workbook unchanged and open
ThisWorkbook.ActiveWorkbook.SaveCopyAs Filename:=CopyFileName
Dim CopiedWb As Workbook
Set CopiedWb = Application.Workbooks.Open(Filename:=CopyFileName)
CopiedWb.Sheets("Settings").Delete
'convert filename to xlsx
CopiedWb.SaveAs Filename:=Replace(ThisWorkbook.FullName, "xlsm", "xlsx"), FileFormat:=xlOpenXMLWorkbook
'close it (we already saved it)
CopiedWb.Close SaveChanges:=False
'kill temporary file with _COPY
Kill CopyFileName
End Sub