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

How can I handle network exceptions in VBA?

    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或者url

当我进入 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 中的网络异常?

我假设您在 .Send 调用后不需要 IE 对象并继续处理 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: 
        '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