VBA-Excel:从XML文件中读取数据

时间:2017-02-05 01:56:29

标签: excel-vba vba excel

我有以下来自REST调用的XML数据,

 <?xml version="1.0" encoding="UTF-8"?>
<response>
    <result>
        <cs>1</cs>                             
        <cs>2</cs>
        <cs>3</cs>
        <cs>4</cs>
    </result>
    <result>
        <br>A</br>                             
        <br>B</br>
    </result>
</response>

我想在excel中读取这些数据, Excel Format

这里cs和br标签的长度不固定,每个数据都会有所不同。

1 个答案:

答案 0 :(得分:0)

这样的事情对你有用。请注意,我并不打算格式化每个单元格: 首先这样做 点击工具&gt;引用。检查这些库 - Microsoft WinHttp Services,版本5.1 - Microsoft xml v6.0

 Sub TestXML()
    URL = "https://example.abc.com" 'Your URL
    AuthorizationCode = "Basic <Password>" 'Please put only encrypted password

    Dim ws As Worksheet
    Dim objHTTP As New WinHttp.WinHttpRequest
    Dim jsonString As String
    Dim Resp As New DOMDocument
    Dim Result As IXMLDOMNode
    Dim i As Integer, j As Integer

    objHTTP.Open "get", URL, False
    objHTTP.SetRequestHeader "Accept", "application/xml"
    objHTTP.SetRequestHeader "Content-Type", "application/xml"
    objHTTP.SetRequestHeader "Authorization", AuthorizationCode
    objHTTP.Send

    Debug.Print objHTTP.Status
    Debug.Print objHTTP.ResponseText

    Set ws = Sheets("sheet1")
    ws.Select
    Range("A1").Select
    Cells.Clear
    Resp.LoadXML objHTTP.ResponseText
    Set lists = Resp.DocumentElement

    x = 2
    y = 1
    For Each listNode In lists.ChildNodes
        x = 2
        Cells(1, y).Value = lists.ChildNodes(y - 1).ChildNodes(0).BaseName
        For Each fieldNode In listNode.ChildNodes
            Cells(x, y).Value = fieldNode.Text
            x = x + 1
        Next fieldNode
        y = y + 1
    Next listNode
End Sub