在 Excel VBA 宏中构建撤消
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/339228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Building Undo Into an Excel VBA Macro
提问by
Excel macros do not seem to allow the use of "undo" after running them. Is there any way to bake undofunctionality into a VBA macro in Excel?
Excel 宏在运行后似乎不允许使用“撤消”。有没有办法将undo功能烘焙到 Excel 中的 VBA 宏中?
采纳答案by e.James
Excel VBA has the Application.OnUndofunction to handle this:
Excel VBA 具有Application.OnUndo处理此问题的功能:
Public Sub DoSomething
... do stuff here
Application.OnUndo "Undo something", "UnDoSomething"
End Sub
Public Sub UnDoSomething
... reverse the action here
End Sub
回答by CABecker
My thought is pretty simple, as the first line in your macro save a copy in a backup directory then close that workbook and reopen the original. If you don't like the results of your macro run, pull up the saved workbook. Keep it simple eh?
我的想法很简单,因为宏中的第一行将副本保存在备份目录中,然后关闭该工作簿并重新打开原件。如果您不喜欢宏运行的结果,请调出保存的工作簿。保持简单吧?
回答by paxdiablo
I always save immediately before running my macros (during testing at least) then, if everything goes pear-shaped, I can just exit without saving and re-open it.
我总是在运行我的宏之前立即保存(至少在测试期间)然后,如果一切都变成梨形,我可以直接退出而不保存并重新打开它。
Baking it into the actual macro, you'll have to basically record the old state of everything that changes (cell contents, formulae, formatting and so on) in a list then have an undo macro which plays back that list in reverse order.
将它烘焙到实际的宏中,您必须基本上记录列表中所有更改(单元格内容、公式、格式等)的旧状态,然后使用撤消宏以相反的顺序播放该列表。
For example if your macro changes a cell C22 contents from "3" to "7" and formatting from "general" to "number, 2 decimals), your list would be:
例如,如果您的宏将单元格 C22 的内容从“3”更改为“7”并将格式从“常规”更改为“数字,2 个小数),您的列表将是:
C22 value 3
C22 format general
Playing this back in reverse order (with another macro) would revert the changes.
以相反的顺序播放(使用另一个宏)将恢复更改。
You could have a whole extra sheet to hold the macro undo information such as:
您可以有一个完整的额外工作表来保存宏撤消信息,例如:
Step Cell Type Value
---- ---- ----- -------
1 C22 value 3
C22 format general
2...
It wouldn't integrate very well with the 'real' undo unfortunately, but I don't think there's any way around that.
不幸的是,它不会与“真正的”撤消很好地集成,但我认为没有办法解决这个问题。

