【问题标题】:Error when Trying to use Try-Catch blocks within excel VBA to get inner exceptions尝试在 excel VBA 中使用 Try-Catch 块来获取内部异常时出错
【发布时间】:2019-02-15 00:15:34
【问题描述】:

我正在使用 excel 和 VBA。我试图从自动化异常中获取内部异常,但首先我需要让 try catch 块工作。看起来我已经完全复制了微软文档中的语法。代码如下:

Try
    Set sm = CreateObject("SpectrumManager.Application")
Catch ex As Exception
    MsgBox ("Can't Create Object") 'placeholder
    'I want to get the inner exception from ex here
End Try

End Try 的错误消息是这样的:“预期:If or Select or Sub or Function or Property or Type or With or Enum or end of statement” Catch 处的错误消息是这样的:“预期:语句结束”

我做错了什么?我在这里先向您的帮助表示感谢。 编辑:我现在意识到 vba 不支持 try-catch 块。这就引出了一个问题,有没有办法从发送的原始异常中获取内部异常?还是在转换为 vba 错误时该信息丢失了?

【问题讨论】:

  • vba 不支持 try catch。 VB.net 确实
  • VBA + Excel + Try Catch的可能重复
  • 任何有关“Visual Basic”的 Microsoft 文档都在 .NET 下归档,并且与 VB.NET 有关; here 是 VBA 的 docs.microsoft。
  • 您是用 VB.NET 还是 VBA 编程?我在 VBA 中期望的编译错误将是 Try 行上的“未定义子或函数”。如果它通过了,它将在Catch 行上出现一般的“语法错误”而失败。

标签: excel vba exception try-catch


【解决方案1】:

VBA 不支持 Try Catch。您可以使用错误处理或更简单的方法

On Error Resume Next
Set sm = CreateObject("SpectrumManager.Application")
On Error GoTo 0
If sm Is Nothing Then
    MsgBox "Can't Create Object"
End If

一个简单的错误处理例程可能如下所示:

Public Sub test()
    Dim sm As Object
    On Error GoTo errhand
    Set sm = CreateObject("SpectrumManager.Application")
    'other code
    Exit Sub
errhand:
    Select Case Err.Number
    Case 429
        MsgBox "Can't Create Object"
        'Case... other errors
    End Select
End Sub

【讨论】:

  • 所以我根据您的回复假设不可能从发送的原始异常中获取内部异常。感谢您的回复。
  • 这是什么意思?例外基本上是底层版本的错误处理程序中带有关联 err.Description 的案例编号。如有误解请见谅。
【解决方案2】:

对于那些愿意考虑将商业第三方作为选项的人,可以选择购买vbWatchDog,它启用了一种带有 VBA 的 Try/Catch 模式。一个可能的样本:

Public Sub Derp(Faceplant As Boolean)
  If Faceplant = False Then
    ErrEx.DoFinally
  End If

  Debug.Print 1 / 0

ErrEx.Catch 91
  Debug.Print "I didn't set something on fire...."
ErrEx.CatchAll
  Debug.Print "Welp. I failed."
ErrEx.Finally
  Debug.Print "Goodbye, cruel world."
End Sub

Relevant documentation

注意:我是 vbWatchDog 的客户。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多