Sub SaveToCSVs()Dim fDir As StringDim wB As WorkbookDim wS As WorksheetDim csvWs As String, csvWb As StringDim extFlag As Long '0 = .xls & 1 = .xlsx extension typesDim fPath As StringDim sPath As String, dd() As StringfPath = "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 = 2Do While (fDir <> "")If Right(fDir, 4) = ".xls" ThenextFlag = 0ElseextFlag = 2End IfIf Right(fDir, 5) = ".xlsx" ThenextFlag = 1ElseextFlag = 2End IfOn Error Resume NextIf extFlag = 2 ThenfDir = DirElseIf extFlag = 1 ThenSet 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.SheetswS.SaveAs sPath & dd(0) & "-" & wS.Name & ".csv", xlCSVNext wSwB.Close FalseSet wB = NothingfDir = DirOn Error GoTo 0End IfLoopEnd 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