繁体   English   中英

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

[英]How do I import XML data using Excel VBA?

我正在尝试从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

Microsoft XML 6.0添加参考( 工具->参考... )。 这将使您拥有类型化变量( Dim book As IXMLDOMNode ),这将为您提供Intellisense。

然后,您可以使用以下代码,对所有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

链接:

参考文献:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM