如何保存 Excel 工作簿的副本?

How to save copy of Excel workbook?

我一直在尝试制作一个宏,在我编辑它的任何数据之前自动保存我的 Excel 工作簿的备份副本。

每次我调用它,即使它成功保存了一个新副本,当它到达末尾时代码停止执行,我尝试在它下面调用的宏也不会执行。

我想当我 运行 创建代码和新的备份版本时,代码继续 运行 在 备份工作簿 而不是主工作簿,所以当我关闭备份工作簿时,我突然结束了代码。

我想保存主工作簿的备份版本,关闭备份版本并继续主工作簿上的代码。

Public Sub BackupWorkbook()

Dim CurrentFile As String, BackupFile As String, DesiredWorkbookName As String
Dim NowDate As String

'Save current code and Excel spreadsheet data
ActiveWorkbook.Save

'Get necessary strings for filenames
CurrentFile = ThisWorkbook.FullName

NowDate = Replace(Format(Now, "dd-mm-yyyy, hh:mm:ss"), ":", ".")
BackupFile = ThisWorkbook.Path & "\" & "Chem Chart Backups" & "\" & "Chemical Chart" _
                & " (" & NowDate & ")" & ".xlsm"

'Save as active workbook to backup file location, then reopen main workbook
ActiveWorkbook.SaveAs BackupFile, FileFormat:=52

Workbooks.Open CurrentFile

'This should close the backup version of workbook that opened because of SaveAs method
Workbooks(DesiredWorkbookName & " (" & NowDate & ")" & ".xlsm").Close SaveChanges:=True

End Sub
Public Sub TestMacros()

Call BackupWorkbook

'If this message box pops up after macro is called, it is successful
MsgBox "Success!" 

End Sub

我用

Sub BackUp()

    Dim BackUpPath As String
        BackUpPath = "Your path"
        
    Dim BackUpFile As String
        BackUpFile = BackUpPath & "BackUp.xlsm"
        
        ThisWorkbook.SaveCopyAs Filename:=BackUpFile
        
End Sub

我在我的项目中多次调用它来根据需要备份文档,这对我来说似乎没问题,我的代码将继续 运行 在原始工作簿中。

我每次都生成一个唯一的文件名,实际上并没有使用“BackUp”作为新工作簿的名称,因为这会覆盖我以前的备份,所以我建议做类似的事情。