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

lor*_*nzo 1 xml excel vba msxml

我正在尝试从这样的 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>
Run Code Online (Sandbox Code Playgroud)

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

我想获得一个 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
Run Code Online (Sandbox Code Playgroud)

Zev*_*itz 6

添加对Microsoft XML 6.0的引用(工具 -> 引用...)。这将允许您拥有类型化变量 ( ),这将为您提供智能感知。Dim book As IXMLDOMNode

然后您可以使用以下代码,它遍历所有book元素,将title和保存author到二维数组中(如果可用),然后将该数组粘贴到 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
Run Code Online (Sandbox Code Playgroud)

链接:

参考: