如何使用Excel VBA导入XML数据?

时间:2015-09-01 10:23:09

标签: xml vba excel-vba msxml excel

我正在尝试从这样的XML文件导入数据:

<library>
<book>
<title>aaa</title>
<author>aaa-author</author>
</book>
<book>
<title>bbb</title>
<author>bbb-author</author>
</book>
<book>
<title>ccc</title>
</book>
</library>

(请注意,第三本书对作者没有价值)

我想获得一个Excel表格,其中每本书的数据显示在一行上。问题是我不明白我如何循环书节点以获得他们的孩子值。

我正在研究这样的代码:

Set mainWorkBook = ActiveWorkbook
Set oXMLFile = CreateObject("Microsoft.XMLDOM")
XMLFileName = "C:\example.xml"
oXMLFile.Load (XMLFileName)
Set Books = oXMLFile.SelectNodes("/book")
For i = 0 To (Books.Length - 1)
   ' I cannot understand this part
Next

1 个答案:

答案 0 :(得分:4)

Microsoft XML 6.0 添加引用(工具 - &gt;引用... )。这将允许您输入类型变量(Dim book As IXMLDOMNode),这将为您提供智能感知。

然后您可以使用以下代码,它遍历所有book元素,将titleauthor保存到二维数组中(如果它们可用),然后将数组粘贴到Excel工作表中:

Dim oXMLFile As New DOMDocument60
Dim books As IXMLDOMNodeList
Dim results() As String
Dim i As Integer, booksUBound As Integer
Dim book As IXMLDOMNode, title As IXMLDOMNode, author As IXMLDOMNode

'Load XML from the file
oXMLFile.Load "C:\example.xml"

'Get a list of book elements
Set books = oXMLFile.SelectNodes("/library/book")
booksUBound = books.Length - 1

'Create a two-dimensional array to hold the results
ReDim results(booksUBound, 1)

'Iterate through all the book elements, putting the title and author into the array, when available
For i = 0 To booksUBound
    Set book = books(i) 'A For Each loop would do this automatically, but we need the
                        'index to put the values in the right place in the array
    Set title = book.SelectSingleNode("title")
    If Not title Is Nothing Then results(i, 0) = title.Text
    Set author = book.SelectSingleNode("author")
    If Not author Is Nothing Then results(i, 1) = author.Text
Next

'Paste the results into the worksheet
Dim wks As Worksheet
Set wks = ActiveSheet
wks.Range(wks.Cells(1, 1), wks.Cells(books.Length, 2)) = results

链接:

参考文献: