【问题标题】:Trap VBE compile error when running editor under VBA control在 VBA 控制下运行编辑器时捕获 VBE 编译错误
【发布时间】:2020-07-25 03:04:19
【问题描述】:

在 VB 控制下运行 excel VBA 时,编译错误会打开 VBE 窗口,标记有问题的行并停止并显示消息框。我想在这些操作发生之前捕获这些错误。

    Dim objVBECommandBar As Object
    Set objVBECommandBar  = Application.VBE.CommandBar
    Set compileMe = objVBECommandBar.FindControl(Type:=msoControlButton, ID:=578) 
    compileMe.Execute

【问题讨论】:

  • 我不相信你可以,因为 VBA 中没有发生错误。

标签: excel vba


【解决方案1】:

我遇到这个问题是因为我遇到了类似或相同的问题。 如果“编译 VBA 项目”选项灰显,则代码将抛出错误。

这是我添加的错误处理:

Private Sub compileVBA()

    Dim objVBECommandBar As Object, compileMe As Object
    Set objVBECommandBar = Application.VBE.CommandBars
    Set compileMe = objVBECommandBar.FindControl(Type:=msoControlButton, ID:=578)
On Error GoTo err
    compileMe.Execute
    Debug.Print "Compiled"
    Exit Sub
err:
    Debug.Print "Failed to compile VBA"
End Sub

【讨论】:

    【解决方案2】:

    这是适合我的代码。如果编译运行成功,则编译命令运行后不会启用。打开以在编译运行时抑制警报。设置为 FALSE 的“Application.DisplayAlerts”不起作用。

    Sub CompileWorkbook()
        Dim objVBECommandBar As Object
        Set objVBECommandBar = Application.VBE.CommandBars
        Dim compileMe As CommandBarButton
        Set compileMe = objVBECommandBar.FindControl(Type:=msoControlButton, ID:=578)
        If compileMe.Enabled = True Then compileMe.Execute
        If compileMe.Enabled = True Then Debug.Print "Error Compiling"
    End Sub
    

    【讨论】:

      【解决方案3】:

      正确的方法是使用“启用”属性:

              Dim compileMe As CommandBarButton
              Set compileMe = Application.VBE.CommandBars.FindControl(Type:=msoControlButton, id:=578)
              If compileMe.Enabled Then compileMe.Execute
      

      【讨论】:

      • 它对我有用。如果您投反对票,请说明原因。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多