簡體   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