如何在VBA中处理网络异常?

时间:2016-10-25 15:39:34

标签: vba excel-vba internet-explorer exception msxml

    Sub test()

    Dim id As String
    id = "user1234"
    Dim PHARMA As String
    PHARMA = "http://xxxx"
    Dim url As String
    url = PHARMA & id


    Dim IE As MSXML2.XMLHTTP60
    Set IE = New MSXML2.XMLHTTP60

    IE.Open "GET", url, False
    IE.send

    'This part could crash the program crash if the user 
    'or the url is wrong, how can I handle this case with exceptions?  

    While IE.readyState <> 4
        DoEvents
    Wend

    Dim HTMLDoc As MSHTML.HTMLDocument
    Dim HTMLBody As MSHTML.HTMLBody

    Set HTMLDoc = New MSHTML.HTMLDocument

    ...

    End Sub

这是我输错了ID或网址的那种情况

当我在网络标签中输入chrome时:

Cache-Control:no-cache
Content-Length:0
Date:Tue, 25 Oct 2016 15:22:04 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/7.0

当我进入答案标签时,我有:

请求没有可用的响应数据(正常,因为url或id错误)

如何在VBA中处理网络异常?

1 个答案:

答案 0 :(得分:0)

我假设您在IE电话之后不需要.Send对象,并在HTMLDocument对象之后处理:

Private Function TryHttpGet(ByVal url As String) As MSHTML.HTMLDocument
    On Error GoTo CleanFail
    Dim document As MSHTML.HTMLDocument        

    With New MSXML2.XMLHTTP60
        .Open "GET", url, False
        .Send

        'not needed per comment: https://stackoverflow.com/questions/40244183#comment67753122_40244183
        'While .ReadyState <> 4 'todo: replace magic value with meaningful constant
        '    DoEvents
        'Wend

        'Set document = ...

    End With

CleanExit:
    'cleanup code here?
    Set TryHttpGet = document
    Exit Sub

CleanFail:
    'error-handling code here
    Set document = Nothing
    Resume CleanExit
End Sub

调用代码可以这样做:

Set document = TryHttpGet(url)
If document Is Nothing Then
    MsgBox "HTTP request failed for URL: " & url & ".", vbExclamation
    Exit Sub
End If