在VBA WinHttpRequest上捕获超时

问题描述 投票:1回答:1

我想设置Timeout值并在使用VBA和Excel时发生此事件。到目前为止,我尝试使用XMLHTTP60和WinHttpRequest:

    Set XMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    With XMLHTTP
        .setTimeouts 11, 11, 11, 11 'Values for testing to get a timeout
        '.setTimeouts TIMEOUT_LRESOLVE, TIMEOUT_LCONNECT, TIMEOUT_LSEND, TIMEOUT_LRECEIVE
        .Open "GET", currenturl, False
        .send
        '.waitForResponse 1 'testing
        If .responseText Like "*PATH_NOT_FOUND*" Or .responseText Like "*OUTSIDE_BOUNDS*" Then
            noroutefound = True
            GoTo skiploop
        End If
        str = Split(.responseText, "{""startTime"":")
        complstr = .responseText
    End With

但是,我无法捕获由超时或超时本身引起的错误。

我怎样才能抓住超时?

excel vba web-scraping error-handling timeout
1个回答
2
投票

在预期错误之前和errHand中添加On Error GoTo errHand的错误处理:确保你有错误处理

'Code
On Error GoTo errHand:
'Code producing error
Exit Sub
errHand

If err.Number <> 0 Then
     Debug.Print err.Message
End If
Exit Sub

如果您有感兴趣的错误编号,可以使用select case err.Number以定制的方式处理您的特定错误,例如:

errHand:

Select Case Err.Number
    Case -2147012894 'Code for Timeout
        Msgbox "Timeout"
    Case -2147012891 'Code for Invalid URL
        Msgbox "Invalid URL"
    Case Else 'Add more Errorcodes here if wanted
        MsgBox "Errornumber: " & Err.Number & vbnewline & "Errordescription: " & Error(Err.Number)
End select
© www.soinside.com 2019 - 2024. All rights reserved.