We help IT Professionals succeed at work.
Get Started

Traversing an XML file with Excel VBA

2,435 Views
Last Modified: 2016-03-03
I have an XML file 'because.xml'. This is a MusicXML file exported from Notion (a score writing tool).

I'm trying to write VBA code to extract the data within the <part> elements, and put them on an Excel sheet in the layout in attached Excel.JPG.

I'm following the examples in J Korol's book Excel 2010 Programming by Example with this code. But having trouble modifying it to my needs.
I would appreciate any help. Please point me in the right direction. (I get a list of data, but not in the right order as per the XML file. Odd)
Thanks!

Sub IterateThruElements()
    Dim xmlDoc As MSXML2.DOMDocument60
    Dim xmlNodeList As MSXML2.IXMLDOMNodeList
    Dim xmlNode As MSXML2.IXMLDOMNode
    Dim myNode As MSXML2.IXMLDOMNode

    ' Create an instance of the DOMDocument
    Set xmlDoc = New MSXML2.DOMDocument60
    xmlDoc.async = False

    ' Load XML information from a file
    strPathToXMLFile = Sheets("Settings").Range("B7").Value     'the path to the XML file
    xmlDoc.Load (strPathToXMLFile)

    ' Find out the number of child nodes in the document
    Set xmlNodeList = xmlDoc.getElementsByTagName("*")

    ' Open a new workbook and paste the data
    Workbooks.Add           
    Range("A1:B1").Formula = Array("Element Name", "Text")
    
    For Each xmlNode In xmlNodeList
    
        For Each myNode In xmlNode.ChildNodes
            If myNode.NodeType = NODE_TEXT Then
                ActiveCell.Offset(0, 0).Formula = xmlNode.nodeName
                ActiveCell.Offset(0, 1).Formula = xmlNode.Text
            End If
        Next myNode

        ActiveCell.Offset(1, 0).Select
        
    Next xmlNode
    
    Columns("A:B").AutoFit

End Sub
    

Open in new window

Excel.JPG
Because.xml
Comment
Watch Question
CERTIFIED EXPERT
Commented:
This problem has been solved!
Unlock 1 Answer and 7 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE