VBA:错误处理程序中出错

时间:2017-06-24 07:15:21

标签: vba excel-vba access-vba excel

我的错误处理程序出了问题。我有一个脚本可以访问一个站点并下载一些文件。我想为它实现一个错误处理程序,因为对站点的更改可能会导致错误抛出。这是我的错误处理程序。

IEError:
    TxtLog ExtractErrLogDir, Environ("UserName") & " " & Now() & " " & Err.Number & ":" & Err.Description ' this is a function I made that writes to txt files
    On Error Resume Next
    IE.Quit
    Set IE = Nothing
    MsgBox "Auto Extract Stop Working:" & vbNewLine & Err.Description

End Sub

另外,我如何制作IE的新实例。

Set IE = New InternetExplorerMedium

我遇到的问题是我无法判断我所做的Internet Explorer实例是否已关闭我的错误处理程序。所以我试图在错误处理程序中创建一个错误处理程序。要关闭IE,如果它出现错误,请忽略它并移动到下一行。但它无法正常工作IE.Quit仍然会抛出处理程序的错误。

2 个答案:

答案 0 :(得分:2)

我就是这样做的

LetsContinue:
    On Error Resume Next
    IE.Quit
    Set IE = Nothing
    MsgBox "Auto Extract Stop Working:" & vbNewLine & Err.Description
    Exit Sub
IEError:
    TxtLog ExtractErrLogDir, Environ("UserName") & " " & Now() & " " & _
    Err.Number & ":" & Err.Description

    Resume LetsContinue

要使用Late Binding创建IE的新实例,请使用此

Dim IE As Object

Set IE = CreateObject("InternetExplorer.Application")

IE.Visible = True

要使用Early Binding创建IE的新实例,请使用此选项。您需要将引用设置为Microsoft Internet Controls

Dim IE As New InternetExplorer

IE.Visible = True

修改

  

Dim IE作为新的InternetExplorer与我的拥有方式相比有什么优势? - Quint 12分钟前

InternetExplorerMediumVista启动以创建以中等完整性级别运行的Internet Explorer实例时,首先使用

IE8

我认为在今天的时代不需要它。

请参阅此MSDN KB

的备注部分
  

<强>说明

     

Windows Internet Explorer 8.在Windows Vista上,要创建以中等完整性级别运行的Internet Explorer实例,请将CLSID_InternetExplorerMedium(在exdisp.idl中定义)传递给CoCreateInstance。生成的InternetExplorerMedium对象支持与InternetExplorer对象相同的事件,方法和属性。

我不确定,我怎么忘记提到这一点,但你也可以这样做而不是On Error Resume Next

LetsContinue:
    If Not IE Is Nothing Then
        IE.Quit
        Set IE = Nothing
    End If
    '~~> Not sure what is the below line for but I have still included it
    MsgBox "Auto Extract Stop Working:" & vbNewLine & Err.Description
    Exit Sub
IEError:
    TxtLog ExtractErrLogDir, Environ("UserName") & " " & Now() & " " & _
    Err.Number & ":" & Err.Description

    Resume LetsContinue

答案 1 :(得分:1)

在例程中抛出错误后,在设置新的错误处理机制之前需要调用Resume。试试这种方式:

IEError:
    TxtLog ExtractErrLogDir, Environ("UserName") & " " & Now() & " " & Err.Number & ":" & Err.Description ' this is a function I made that writes to txt files
    Resume TryQuit ' <-- call Resume to be able to setup new err-handling

TryQuit:
    On Error Resume Next
    IE.Quit
    Set IE = Nothing
    MsgBox "Auto Extract Stop Working:" & vbNewLine & Err.Description
End Sub