vbaexcelxmlhttprequestcreateobject

VERY strange behavior on createobject("HTMLFILE")!


I don't understand why I'm getting this strange behavior! When creating and assigning the htmlfile object the function gives back a blank object ("nothing") and when I am running the code line by line it just runs automatically even when I don't press F8 to run the next line... It gives no error whatsoever! Any ideas as to what might be happening?

Line where the strange behavior starts: Set htmlObj = CreateObject("HTMLFILE")

Public Function XMLHTTP_Request(Method As String, URL As String, Optional PostData As String, Optional StrCookie As String) As HTMLDocument

Dim oXMLHTTP As Object, htmlObj as object
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP")
oXMLHTTP.Open Method, URL, False
oXMLHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
oXMLHTTP.setRequestHeader "Cookies", StrCookie

On Error GoTo ErrorHandler
oXMLHTTP.send (PostData)
On Error GoTo 0

While oXMLHTTP.ReadyState <> 4: DoEvents: Wend
While oXMLHTTP.Status <> 200: DoEvents: Wend

Set htmlObj = CreateObject("HTMLFILE")

htmlObj.body.innerHTML = oXMLHTTP.responseText
Set XMLHTTP_Request = htmlObj

End Function

Solution

  • Repeated calls to the function will cause multiple calls to the CreateObject function. The oXMLHTTP and htmlObj object vars could be made static or library references could be included and the variable declaration changed to Early Binding.

    Early binding requires that the following non-default library references are added through the VBE's Tools ► References command.

    Module1 code sheet:

    Option Explicit
    
    Sub main()
        Debug.Print Left(XMLHTTP_Request("http//example.com").body.innerText, 512)
    End Sub
    
    Public Function XMLHTTP_Request(URL As String, _
                                    Optional Method As String = "POST", _
                                    Optional PostData As String = "", _
                                    Optional StrCookie As String = "") As HTMLDocument
        Dim oXMLHTTP As New MSXML2.XMLHTTP60
        Dim htmlObj As New HTMLDocument
    
        oXMLHTTP.Open Method, URL, False
        oXMLHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
        oXMLHTTP.setRequestHeader "Cookies", StrCookie
    
        oXMLHTTP.send PostData
    
        If oXMLHTTP.Status <> 200 Then Exit Function
    
        htmlObj.body.innerHTML = oXMLHTTP.responseText
    
        Set XMLHTTP_Request = htmlObj
    
    End Function
    

    Running the main() sub procedure will output the first 512 characters of the web page's text to the Immediate window ([Ctrl]+G).