2015-03-13 153 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