使用Excel-VBA获取HTML源代码

l--*_*''' 1 string url excel vba excel-vba

我想将excel VBA表单指向某些URL,获取HTML源并将该资源存储在字符串中.这是可能的,如果是的话,我该怎么做?

Gar*_*ill 7

是.一种方法是使用MSXMLDLL - 为此,您需要Microsoft XML通过Tools-> References添加对库的引用.

这是一些显示给定URL内容的代码:

Public Sub ShowHTML(ByVal strURL)
    On Error GoTo ErrorHandler
    Dim strError As String
    strError = ""
    Dim oXMLHTTP As MSXML2.XMLHTTP
    Set oXMLHTTP = New MSXML2.XMLHTTP
    Dim strResponse As String
    strResponse = ""

    With oXMLHTTP
        .Open "GET", strURL, False
        .send ""
        If .Status <> 200 Then
            strError = .statusText
            GoTo CleanUpAndExit
        Else
            If .getResponseHeader("Content-type") <> "text/html" Then
                strError = "Not an HTML file"
                GoTo CleanUpAndExit
            Else
                strResponse = .responseText
            End If
        End If
    End With

CleanUpAndExit:
    On Error Resume Next ' Avoid recursive call to error handler
    ' Clean up code goes here
    Set oXMLHTTP = Nothing
    If Len(strError) > 0 Then ' Report any error
        MsgBox strError
    Else
        MsgBox strResponse
    End If
    Exit Sub
ErrorHandler:
    strError = Err.Description
    Resume CleanUpAndExit
End Sub
Run Code Online (Sandbox Code Playgroud)