【问题标题】:Error handling not working for slide ID错误处理不适用于幻灯片 ID
【发布时间】:2018-08-30 20:48:09
【问题描述】:

无法处理我的代码中的异常。我已经编写了下面的代码来将 powerpoint 表的内容传输到数组中,但它一直抛出一个异常说

幻灯片(未知成员):请求无效。幻灯片 ID 无效。

我输入了错误句柄来尝试跳过它,因为在出​​现错误的情况下条目是否留空对我来说并不重要。但是,我无法让它通过这个错误! (接下来我不能使用简历)。任何帮助都会很棒。

'loop through table and store values to a temporary array in order to sort it
'NOTE that the Table starts at (1,1) and the  storage array starts at (0,0) (see "j")
For j = 1 To oTbl.Rows.Count

    'First check that the string being stored is a hyperlink and not an empty cell
    If Not (oTbl.Cell(j, 2).Shape.TextFrame.TextRange.ActionSettings(ppMouseClick).Hyperlink.SubAddress) = "" Then

        'create a temp variable to operate on the hyperlink address in each row in the table
        subAd = oTbl.Cell(j, 2).Shape.TextFrame.TextRange.ActionSettings(ppMouseClick).Hyperlink.SubAddress

        'Find the CURRENT slideIndex and store in column 1 (for sorting)
        'write error condition for if the slideID points to a slide that has been deleted
On Error GoTo errCatch
        pLinkNumber = Left(subAd, InStr(subAd, ",") - 1)
        aStorage(j - 1, 1) = ActivePresentation.slideS.FindBySlideID(CLng(pLinkNumber)).SlideIndex

        'store the CURRENT hyperlink address as column 0 (after defining colum 1 for error handling reasons)
        aStorage(j - 1, 0) = subAd

    Else
errCatch:
    End If
Next j

【问题讨论】:

    标签: vba error-handling runtime-error powerpoint


    【解决方案1】:

    你的错误路径与你的“快乐路径”交织在一起。

    良好的错误处理应该在它自己的执行路径中。

    我会将 errCatch 标签重命名为例如Skip,然后在程序底部添加:

        Exit Sub
     ErrCatch:
         Err.Clear
         Resume Skip
    

    现在“快乐路径”在Exit Sub 结束,“错误路径”跳转到这个小子程序,它清除错误并恢复到Skip 标签。该“恢复”部分告诉 VBA 运行时“嘿,我们不再处于错误状态” - 当前您的代码进入错误状态,然后没有任何信息告诉 VBA 您已完成处理该错误,所以 errCatch 得到跳转到,然后 VBA 将“快乐路径”理解为错误处理子例程:它希望您处理错误并最终 Resume 到“快乐路径”,但发生的是错误本质上是未处理,并且错误状态持续到下一个循环迭代。

    这就是说On Error GoTo 语句可能应该被拉出循环范围,假设oTbl.Rows.Count 没有失败的理由(或者是吗?)。每次迭代都运行它是多余的。


    我不能使用继续下一个

    为什么不呢?在其有限的范围内,它是一个很好的工具!

    Private Function GetSlideByID(ByVal id As Long) As Slide
        On Error Resume Next
        Set GetSlideByID = ActivePresentation.slideS.FindBySlideID(id)
    End Function
    

    现在你可以这样做了:

    Dim thisSlide As Slide
    Set thisSlide = GetSlideByID(CLng(pLinkNumber))
    If Not thisSlide Is Nothing Then
        aStorage(j - 1, 1) = thisSlide.SlideIndex
        aStorage(j - 1, 0) = subAd
    End If
    

    不再需要On Error 语句行标签!

    【讨论】:

    • 哇,多么棒的答案!谢谢你的帮助,成功了。
    • @Stuart 随时将此答案标记为“已接受”,方法是单击帖子顶部附近投票按钮旁边的空心复选标记!
    • 再次感谢您。它确实简化了代码。我实现了您建议的功能。仍在学习 VBA,感谢您的帮助!
    • @Stuart 允许我无耻地插入我的 VBIDE 插件项目 - 请参阅我个人资料中的链接 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2020-03-28
    • 2019-08-25
    • 2012-12-08
    • 2013-08-20
    • 2013-09-12
    相关资源
    最近更新 更多