在createobject(“HTMLFILE”)上有非常奇怪的行为!

时间:2016-07-29 16:43:31

标签: excel vba excel-vba xmlhttprequest createobject

我不明白为什么我会遇到这种奇怪的行为! 在创建和分配htmlfile对象时,该函数返回一个空白对象(“无”),当我逐行运行代码时,即使我没有按F8运行下一行,它也会自动运行... 它没有任何错误! 关于可能发生的事情的任何想法?

奇怪行为开始的行: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

1 个答案:

答案 0 :(得分:1)

重复调用该函数将导致多次调用CreateObject function。 oXMLHTTP和htmlObj对象变量可以是静态的,也可以包含库引用,变量声明变为Early Binding。

早期绑定要求通过VBE的工具►参考命令添加以下非默认库引用。

  • Microsoft HTML对象库
  • Microsoft Internet Controls
  • Microsoft XML 6.0(您自己的版本可能略有不同)。

Module1代码表:

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

运行main()子程序会将网页文本的前512个字符输出到立即窗口([Ctrl] + G)。