Export all sheets/pages in multiple Excel files/workbooks as CSV files

qubodup 2010-01-15

I have a bunch of Excel files, I need all of their sheets exported. This is how I do it: Open Excel (with no file open), Press Alt+F11, insert code from below, goto Tools/Macro/Macros and run the "Export_Sheets_as_CSV" macro.

' Global variables
Public FileCounter As Long
Public FileNameArray

Sub Export_Sheets_as_CSV()
'
' Export_CSP_CSV Macro
' Export all Sheets as CSV files
'

GetFileNames
For i = 1 To FileCounter
' Open file i
Workbooks.Open FileName:=FileNameArray(i)
ProcessFile (FileNameArray(i))
' Couldn't figure out how to close by name.. so I'm closing the 'current' workbook
ActiveWorkbook.Close False
'Workbooks(FileNameArray(i)).Close SaveChanges:=False
Next

End Sub

Sub GetFileNames()
' Select files and create array of their names

FileNameArray = Application.GetOpenFilename(, , , , True)
FileCounter = UBound(FileNameArray)

End Sub

Sub ProcessFile(FileName)
' Export every sheet in the file

' Loop through and export sheets
For x = 1 To Sheets.Count
Sheets(x).Select
ActiveWorkbook.SaveAs FileName:=FileName & Sheets(x).Name & ".csv", FileFormat:=xlCSV, CreateBackup:=False
Next x

End Sub


I learned on the web how to: close the active file/workbook, do something with every sheet, merge/combine/concatenate/join multiple Excel files (or just do something with many Excel files).

PS: Please, oh please do post improvements to this script if you make any! :)

PPS: Newlines or "\n"s or "LF"s, which you can insert by pressing Alt+Enter in Excel, get exported as well. This causes trouble of course, as a newline indicates a new row in a CSV file. They need to be removed.

I open the affected files in Notepad++ and enable "View/Show all characters" to see them:



The obvious pattern is that unwanted line breaks only have a newline/"\n"/"LF", while wanted also have a carriage return/"\r"/"CR". The solution to my problem is to replace all newlines that have no carriage returns directly before them with nothing. The regular expression to find what I just described is "[^\r]\n". However, it won't work in Notepad++. I don't know why. This wiki page is unfortunately unable to help. My solution is to use the extended search function to first replace "\r\n" with "thisStringIsSafe", then "\n" with "" and then "thisStringIsSafe" with "\r\n".

I learned about newlines and carriage returns here, and was able to construct a regular expression thanks to this overview.

No comments:

Post a Comment