Sub SaveToCSVs()
Dim fDir As String
Dim wB As Workbook
Dim wS As Worksheet
Dim csvWs As String, csvWb As String
Dim extFlag As Long '0 = .xls & 1 = .xlsx extension types
Dim fPath As String
Dim sPath As String, dd() As String
fPath = "C:\Documents and Settings\mvasas\Desktop\VBA\Dev\_My_Projects\"
sPath = "C:\Documents and Settings\mvasas\Desktop\VBA\Dev\_My_Projects\"
fDir = Dir(fPath)
extFlag = 2
Do While (fDir <> "")
If Right(fDir, 4) = ".xls" Then
extFlag = 0
Else
extFlag = 2
End If
If Right(fDir, 5) = ".xlsx" Then
extFlag = 1
Else
extFlag = 2
End If
On Error Resume Next
If extFlag = 2 Then
fDir = Dir
ElseIf extFlag = 1 Then
Set wB = Workbooks.Open(fPath & fDir)
csvWb = wB.Name
'Be careful here, this split will split a string into an array
'with a dot (.) delimeter. The string is the name of the workbook
'testing was performed on workbooks where the only dots were at
'the extension ie: CSVSAVERTESTFILE.xlsx. If there is a file with
'a name like, CSV.SAVER.TEST.FILE.xlsx, the file will be renamed:
'CSV.Sheet1.csv as the code takes the first String value in the
'array as the new name.
dd = Split(csvWb, ".")
For Each wS In wB.Sheets
wS.SaveAs sPath & dd(0) & "-" & wS.Name & ".csv", xlCSV
Next wS
wB.Close False
Set wB = Nothing
fDir = Dir
On Error GoTo 0
End If
Loop
End Sub
Wednesday, January 28, 2015
VBA - How to convert xls, xlsx files in a directory to csv
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment