Excel VBA XML – 文档未加载

我正尝试从API XML数据拉在Excel中创build数据表。 在下面的代码之前,我做了API调用,下面的第一行提供了一个包含XML数据的msgbox(以便部分工作)。

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吗?

你想要的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