如何保存不带宏的Excel文件副本,然后复制原始文件?

时间:2019-01-29 12:02:30

标签: excel vba

我要执行以下操作-

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

此代码存在以下问题:

  1. 打开结果文件时,它说文件格式不等于文件内容
  2. 它不会再次打开原始书籍(Application.Workbooks.Open行未执行)

我该如何解决?

1 个答案:

答案 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