Rachel
Rachel

Reputation: 1967

Convert all XML files in a directory to XLS via VBA

I have around 950 .xml files in a directory. I can open the .xml files with Excel without any issues. But I'd like to convert all files individually to .xls (or .csv). I searched the forum and found a few answers (see e.g. here and here) but could not make it work so far.

The closest I got to what I need is the following code:

Sub xmltoxl()
    Dim f As String
    Dim wbk As Workbook
    Dim s As Integer
    Dim tBook As Workbook
    Dim MySht As Worksheet

    Set tBook = ThisWorkbook
    Set MySht = tBook.Sheets(1)
    MySht.Cells.ClearContents

    f = Dir("C:\Users\Kanye\Downloads" & "\*.xml")
    s = 0

    Do While Len(f) > 0
        Set wbk = Workbooks.OpenXML("C:\Users\Kanye\Downloads" & "\" & f)
        If s = 0 Then
           wbk.Sheets(1).Cells.Copy Destination:=MySht.Cells
           LastRow = MySht.Range("A" & Rows.Count).End(xlUp).Row
           MySht.Range("Z1:Z" & LastRow) = f
        Else
           LastRow = MySht.Range("A" & Rows.Count).End(xlUp).Row
           NextRow = LastRow + 1

           wbkLastRow = wbk.Sheets(1).Range("A" & Rows.Count).End(xlUp).Row

           wbk.Sheets(1).Rows("1:" & wbkLastRow).Copy Destination:=MySht.Rows(NextRow)

           NewLastRow = MySht.Range("A" & Rows.Count).End(xlUp).Row
           MySht.Range("Z" & NextRow & ":Z" & NewLastRow) = f
        End If
        MySht.Columns("Z").Cut
        MySht.Columns("A").Insert

        s = s + 1
        wbk.SaveAs Filename:="C:\Users\Kanye\Downloads\Test" & s & ".csv"
        wbk.Close False
        f = Dir()
    Loop

End Sub 

However, when I run it, I get back an error after the first .xml is opened in the directory. Any ideas on how to solve this?

Upvotes: 2

Views: 1239

Answers (2)

YasserKhalil
YasserKhalil

Reputation: 9538

Try this code

Sub XMLTOCSV()
Dim f           As String
Dim p           As String
Dim s           As Integer

p = Environ("USERPROFILE") & "\Downloads" & "\"
f = Dir(p & "*.xml")
s = 0

Application.ScreenUpdating = False
    Do While Len(f) > 0
        s = s + 1
        ConvertXMLtoCSV p & f, p & "Test" & s & ".csv"
        f = Dir()
    Loop
Application.ScreenUpdating = True
End Sub

Sub ConvertXMLtoCSV(xmlFile, csvFile)
Dim xlApp       As Application
Dim xlBook      As Workbook

Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.OpenXML(xmlFile, 2)
xlBook.SaveAs csvFile, 6
xlBook.Close False
xlApp.Quit
End Sub

Upvotes: 4

user4039065
user4039065

Reputation:

I've found the most effective method of Workbook.SaveAs is to ignore any extension and let the FileFormat argument choose that for you.

...
wbk.SaveAs Filename:="C:\Users\Kanye\Downloads\Test" & s, fileformat:=xlcsv
wbk.Close savechanges:=False
...

Upvotes: 2

Related Questions