我正在构建一个 C# 应用程序,它需要通过 Office Interop 与 Excel 电子表格进行交互。我想获得对完整撤消堆栈的访问权限,以便我可以对工作表进行一系列更改,然后在必要时一次将它们回滚。我看到 Interop 程序集中的 Word 文档对象具有 UndoRecord 和其他一些细节,包括 Undo 函数。例如,我可以调用带有参数的 Microsoft.Office.Interop.Word._Document.Undo() 来撤消多个操作。另一方面,Excel 的撤消功能看起来更加有限。当然,有 Microsoft.Office.Interop.Excel._Application.Undo(),但它只进行一次操作,如果再次调用,则执行“重做”而不是深入堆栈。
我在网上找到了代码,其中 VBA 开发人员为 Excel 编写了他们自己的撤消历史记录,因为这是获得所需功能的唯一方法。不过,对于 C#,我没有看到类似的东西。有什么方法可以模仿 Word 的互操作撤消在 Excel 中的工作方式吗?
请您参考如下方法:
可惜,适用于 Word 的却不适用于 Excel。可能是因为写 Word VBA 的人多了 :)。看这个John Walkenbach page了解 Excel VBA(和互操作)的可能性。以下是他的部分描述:
Making the effects of your subroutines undoable isn't automatic. Your subroutine will need to store the previous state so it can be restored if the user choose the Edit Undo command. How you do this will vary, depending on what the subroutine does. In extreme cases, you might need to save an entire worksheet. If your subroutine modifies a range, for example, you need only save the contents of that range.
编辑:
有 Application.Undo 方法,但它非常有限。这是 Excel 2010 VBA 帮助中的描述:
Application.Undo Method
Cancels the last user-interface action.
Remarks This method undoes only the last action taken by the user before running the macro, and it must be the first line in the macro. It cannot be used to undo Visual Basic commands.
特别是关于 Interop,我确信 VBA 本身没有任何可用的东西。
