Search code examples
excelxmlvbaimportbatch-processing

Batch Import XML Files to Excel Workbook (VBA)


Mission: I have a folder of some 90 XML files received weekly that all need consolidated as individual pages in an excel workbook (excel 2016). To make that clear, the resulting workbook should have 90 pages (or however many XML files I need to import that week), with each sheet matching the file name of the XML matched to it.

I have found several mentions on how to batch import XMLs into a single sheet or table, but other than the kutools extensions that never work for me, I can't seem to find anything that imports the files as individual sheets.

Is this even possible? I am a complete VBA scrub, but if there's a way to do this that doesn't involve me manually clicking Data -> Get Data -> From File -> From XML File and going through all the dialogues for each individual file, I would love to hear it.

Thank you in advance!


Solution

  • Here's a very basic example:

    Sub Tester()
        
        Const FLDR As String = "C:\Tester\tmp\"
        
        Dim f, wb
        Application.DisplayAlerts = False
        f = Dir(FLDR & "*.xml")
        Do While Len(f) > 0
            Debug.Print(f) 'output filename to Immediate panel
            Application.DisplayAlerts = False
            Set wb = Workbooks.OpenXML(Filename:=FLDR & f, LoadOption:=xlXmlLoadImportToList)
            Application.DisplayAlerts = True
            wb.Sheets(1).Name = Replace(f, ".xml", "")
            wb.Sheets(1).Copy after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
            wb.Close False
            f = Dir()
        Loop
    End Sub