【问题标题】:On error -> cancel what already done出错时 -> 取消已经完成的操作
【发布时间】:2015-06-24 10:43:54
【问题描述】:

有没有办法对代码说,每次出现错误时,取消之前所做的事情? 例如,我有一个创建 6 个工作簿的代码,当代码的一半出现错误时,我必须取消每个工作簿并再次启动宏!

提前致谢

【问题讨论】:

    标签: excel error-handling vba


    【解决方案1】:

    你可以试试:

    Application.UnDo
    

    在您的错误代码中。 它并不总是有效。

    【讨论】:

      【解决方案2】:

      VBA 执行会导致撤销历史记录被删除

      • 以任何方式更改界面的代码都会清除撤消缓冲区(堆栈)
      • 历史是一个字符串列表(或集合)

        • Application.CommandBars("Standard").Controls("&Undo").Control.ListCount 为 0

      但你也许可以做这样的事情

      Option Explicit
      
      Public Sub makeFiles()
          Dim i As Long, currentWB As Long, newWBs As Long
      
          On Error GoTo cancelAction
      
          currentWB = Workbooks.Count
          For i = 1 To 6
              Workbooks.Add
              newWBs = newWBs + 1
              ActiveSheet.Cells(1, 1).Value = 4
      
              'generate an error
              If i = 3 Then Workbooks.Item(Workbooks.Count + 1).Activate
          Next
      
      cancelAction:
      
          Do While newWBs > 0     'Workbooks.Count > 1
              Workbooks(currentWB + newWBs).Close False
              newWBs = newWBs - 1
          Loop
      
      End Sub
      

      【讨论】:

        猜你喜欢
        • 2020-05-16
        • 2020-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-23
        相关资源
        最近更新 更多