在VBA控制下运行编辑器时陷阱VBE编译错误

时间:2015-09-04 05:05:06

标签: excel-vba vba excel

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

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

3 个答案:

答案 0 :(得分:0)

我遇到了这个问题,因为我有类似或相同的问题。 如果编译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

答案 1 :(得分:0)

这是对我有用的代码。如果编译成功运行,则运行后将不会启用编译命令。运行编译时打开以取消显示警报。设置为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

答案 2 :(得分:-1)

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

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