Save “backup copy” of workbook without committing changes to Excel?

大憨熊 提交于 2019-12-08 07:26:45

问题


I'm not sure this is possible but maybe I'm missing something obvious.

I want to programmatically, and invisibly save a "backup" copy of the workbook in it's current state, without "committing" the changes to Excel or destroying the Undo history.

Example Scenario:

  1. User opens c:\folder1\workbookA.xlsm
  2. User makes changes to the workbook that they may not wish to commit to.
  3. My sub begins due to timer or other event, and in the background, saves a copy of the workbook as c:\folder2\workbookB.xlsm

The catch is that this the action of creating a backup copy needs to be "invisible" to the user, so that if they later Save or close discarding changes, the result will be the same as if my backup copy was not created.

This means:

  • the filename in the titlebar has not changed,
  • Ctrl+Z/Undo still works,
  • if the user closes the workbook, they are still prompted to Save Changes?
    (easy with workbook.Saved = False)
    • if they choose Yes then the workbook is saved like normal
      (replacing the file at c:\folder1\workbookA.xlsm.)
    • if they choose No, the workbook is closed and the file at c:\folder1\workbookA.xlsm is still in it's original, unmodified form, as if no changes were made in Step #2.

As far as I know, workbook.SaveAs always updates the name of the workbook and clears the "undo" history, so there's no way to close the file without keeping changes. Thanks!


回答1:


I was sitting there thinking, "if only there was a Save Copy As… option..."

Then I realized the solution was right in front of me: the .SaveCopyAs method.


Workbook.SaveCopyAs Method (Excel)

Saves a copy of the workbook to a file but doesn't modify the open workbook in memory.

Syntax

expression.SaveCopyAs(Filename)

  • expression - a variable that represents a Workbook object.
  • Filename Variant (Required) - Specifies the file name for the copy.

Note: The documentation mistakenly says the Filename parameter is optional (which wouldn't make sense).
      I've edited the MSDN page, pending approval.



来源:https://stackoverflow.com/questions/50883674/save-backup-copy-of-workbook-without-committing-changes-to-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!