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 techguruplus telegram group Join Our WhatsApp Group techguruplus whatsapp group
Nazim Khan - Author Image

Nazim Khan (Author) 📞 +91 9536250020
[MBA in Finance]

Nazim Khan is an expert in Microsoft Excel. He teaches people how to use it better. He has been doing this for more than ten years. He is running this website (TechGuruPlus.com) and a YouTube channel called "Business Excel" since 2016. He shares useful tips from his own experiences to help others improve their Excel skills and careers.

Leave a Comment