VBA Code to Import Data from an XML File into Excel

VBA Code:

' VBA Code to Import Data from an XML File into Excel

Sub ImportDataFromXML()
    Dim ws As Worksheet
    Dim xmlFilePath As String
    Dim xmlDoc As Object
    Dim xmlRoot As Object
    Dim xmlNode As Object
    Dim row As Long
    
    ' Set the worksheet to import the data
    Set ws = ThisWorkbook.Worksheets("Sheet1") ' Replace with the name of your worksheet
    
    ' Specify the path of the XML file to import data from
    xmlFilePath = "C:\Path\to\your\XML\File.xml" ' Replace with the path of your XML file
    
    ' Clear the existing data in the worksheet
    ws.Cells.Clear
    
    ' Create a new XML document object
    Set xmlDoc = CreateObject("MSXML2.DOMDocument")
    
    ' Load the XML file
    If xmlDoc.Load(xmlFilePath) Then
        ' Get the root element of the XML document
        Set xmlRoot = xmlDoc.DocumentElement
        
        ' Set the initial row for writing the data
        row = 1
        
        ' Loop through the child nodes of the root element
        For Each xmlNode In xmlRoot.ChildNodes
            ' Write the node values to the worksheet
            ws.Cells(row, 1).Value = xmlNode.SelectSingleNode("NodeName1").Text ' Replace with the appropriate node name
            ws.Cells(row, 2).Value = xmlNode.SelectSingleNode("NodeName2").Text ' Replace with the appropriate node name
            ' Add more lines for additional node values
            
            ' Increment the row counter
            row = row + 1
        Next xmlNode
    Else
        ' Display an error message if the XML file couldn't be loaded
        MsgBox "Failed to load XML file."
    End If
    
    ' Format the imported data if needed
    
    ' Display a message
    MsgBox "Data has been imported from the XML file."
End Sub


Check All VBA Codes

Join Our Telegram Group

Join the TechGuruPlus Telegram group

Join Our WhatsApp Group

Join the TechGuruPlus WhatsApp group
Nazim Khan, founder of TechGuruPlus.com

— Founder & Editor, TechGuruPlus.com
[MBA in Finance]

Nazim Khan has spent over ten years working with Excel, Tally and office documentation in accounts, finance and MIS roles. He has been running TechGuruPlus.com since 2016, where he publishes free editable templates for office work, and the YouTube channel Business Excel. He has trained more than 50,000 people online. Every template on this site is built and checked by him before it is published.

Contact  Â·  Excel Course

Leave a Comment