2015-03-13 137 views
1

我想从API XML数据拉的Excel中创建数据表。在下面的代码之前,我做了API调用,下面的第一行用XML数据提供了一个msgbox(以便部分看起来正在工作)。Excel VBA XML - 文档未加载

MsgBox httpReq.responseText 
Dim xDoc As MSXML2.DOMDocument 
Set xDoc = New MSXML2.DOMDocument 
xDoc.async = False 
xDoc.validateOnParse = False 
If xDoc.Load(httpReq.responseText) Then 
    'Do something 
Else 
    MsgBox "Document failed to load." 
End If 

不幸的是,我然后继续击中If/Then(即文档未加载)的Else方。我的语法错了吗?在我的研究工作中,似乎.Load()的参数通常是一个文件或URL - 我可以不使用httpReq.responseText代替文件名或URL吗?

回答

2

你想要LoadXML方法:

If xDoc.LoadXML(httpReq.responseText) Then 
    MsgBox "Do something" 
Else 
    MsgBox "Document failed to load." 
End If 

工作例如:

Sub test() 

    Dim httpReq As Object 
    Set httpReq = CreateObject("winhttp.winhttprequest.5.1") 

    httpReq.Open "GET", "http://xmlgw.companieshouse.gov.uk/examples/namesearch_req.xml", False 
    httpReq.send 

    Dim xDoc As MSXML2.DOMDocument 
    Set xDoc = New MSXML2.DOMDocument 

    xDoc.async = False 
    xDoc.validateOnParse = False 

    If xDoc.LoadXML(httpReq.responseText) Then 
     MsgBox "Do something" 
    Else 
     MsgBox "Document failed to load." 
    End If 

End Sub 
+0

真棒!非常感谢! – rryanp 2015-03-13 17:12:28