由于缺少特权而“捕获”错误?

时间:2014-06-13 12:22:26

标签: excel vba excel-vba excel-2010

我在VBA脚本中有以下代码(在Excel [openxml] -Sheet中):

  For Each Co In ThisWorkbook.Worksheets("META").ChartObjects
        Co.Delete
    Next Co

当我第一次打开Excel文件时,“Co.Delete”会抛出“拒绝访问” - 错误(“您没有足够的权限来完成此操作”)

当我选择另一张表并返回到第一张表,然后像以前一样点亮SAME按钮时,调用该方法不会抛出此错误。它对我来说看起来很像Excel-Bug。

我知道没有尝试...在VBA中捕获并且我知道我可以插入“on error resume next”但我只是不想:)

是否有一种不同的方法,如方法“if (Co.DeletionAllowed) Then”?

1 个答案:

答案 0 :(得分:1)

AFAIK没有办法提前发现是否会收到此错误。

这是捕获和处理错误的方法:

    On Error GoTo ErrorHandler
    For Each Co In ThisWorkbook.Worksheets("META").ChartObjects
        Co.Delete
    Next Co

    'rest of your procedure goes here...

    'Now here comes the bit that does the error handling -- equivalent to a catch block
ExitProcedure:
    On Error Resume Next
    'Clean-up code goes here
    Exit Sub
ErrorHandler:
    Select Case Err.Number
    Case 12345 ' or whatever error number you are getting
        'Permission denied when deleting ChartObject. Ignore and skip to next statement.
        Resume Next ' or whatever else you want to do
    Case Else
        MsgBox "Unexpected error! See Immediate window for detail.s"
        Debug.Print Err.Number, Err.Source & ", Procedure lkjh of Module Module1", Err.Description, Err.HelpFile, Err.HelpContext
        'Or whatever else you want to do to log unexpected errors.
    End Select
    Resume ExitProcedure
    Resume

Why that second Resume?