troubleshooting Question

Traversing an XML file with Excel VBA

Avatar of hindersaliva
hindersalivaFlag for United Kingdom of Great Britain and Northern Ireland asked on
Microsoft ExcelXMLVisual Basic ClassicVBA
7 Comments1 Solution2446 ViewsLast Modified:
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)

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

End Sub

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 7 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros