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\common\Texas" & "\*.xml") s = 0 Do While Len(f) > 0 Set wbk = Workbooks.OpenXML("C:\Users\Kanye\Downloads\common\Texas" & "\" & 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("L" & NextRow & ":Z" & NewLastRow) = f End If s = s + 1 Filename:="C:\Users\Kanye\Downloads\common\Texas\Test" & s & ".csv" wbk.Close False f = Dir() Loop End Sub
This vba code turns 1000 or so XML files into 1 CSV. I'd like to tweak it so I can ingest it to a SQL database but need help figuring out the below:
- When this code is run it produces a column header, individual rows for each filename, and a blank row. Can the column header be left out after the second filename is converted and blank rows be left out completely?
- the NewLastRow code produces an the XML filename but I need to make this more unique for SQL. Is there a way I can add a new column with the Filename that concatenates a "-1" for the first filename in sequence? Eg. Say I run the code and there's 3 rows for Filename1, I'd like Row 1 to have a column value of Filename-1, Row 2 Filename-2, Row 3 Filename-3. The tricky part is not all filenames have 3 rows, some may have 1 or 8.
No comments:
Post a Comment