用VBA可以恢复,但不能通过Excel内置的功能自动实现。您可以使用VBA代码记录下运行宏程序前单元格或单元格区域原先的内容,在“撤销”命令中调用以恢复程序运行前的状态。
您可以使用Application对象的OnUndo方法作为宏程序结束前的最后一个代码,该方法允许您指定出现在“撤销”菜单项中的文本以及点击该文本后所运行的过程。如下面的代码所示:
Application.Onundo “撤销最后一个宏”,”恢复宏程序”
为说明上述方法,下面列出了一个完整的示例。示例的完整代码以及代码说明如下:
‘**************************************************
Type RangeCellInfo '自定义类型存储宏运行所作出的改变
CellContent As Variant
CellAddress As String
End TypePublic OrgWB As Workbook
Public OrgWS As Worksheet
Public OrgCells() As RangeCellInfo
‘**************************************************
Sub EditRange()
' 在所有被选取的单元格中插入X
Dim i As Integer, cl As Range
If TypeName(Selection) <> "Range" Then Exit Sub
Application.ScreenUpdating = False
ReDim OrgCells(Selection.Count)
Set OrgWB = ActiveWorkbook
Set OrgWS = ActiveSheet
i = 1
‘记录下宏程序对工作表作出改变前的状态
For Each cl In Selection
OrgCells(i).CellContent = cl.Formula
OrgCells(i).CellAddress = cl.Address
i = i + 1
Next cl
‘在所选单元格中填允X
Selection.Formula = "X"
‘指定在“撤销”菜单项中的文字及选择该命令时所执行的宏程序
Application.OnUndo "撤销最后运行的宏过程操作", "UndoEditRange"
End Sub
‘**************************************************
‘恢复工作表原先的状态
Sub UndoEditRange()
Dim i As Integer
Application.ScreenUpdating = False
On Error GoTo NoWBorWS
OrgWB.Activate
OrgWS.Activate
On Error GoTo 0
'恢复宏运行所作的改变
For i = 1 To UBound(OrgCells)
Range(OrgCells(i).CellAddress).Formula = OrgCells(i).CellContent
Next i
Set OrgWB = Nothing
Set OrgWS = Nothing
Erase OrgCells
NoWBorWS:
End Sub