Wednesday, January 28, 2015

VBA - How to convert xls, xlsx files in a directory to csv

  1. Sub SaveToCSVs()

  2. Dim fDir As String
  3. Dim wB As Workbook
  4. Dim wS As Worksheet
  5. Dim csvWs As String, csvWb As String
  6. Dim extFlag As Long '0 = .xls & 1 = .xlsx extension types
  7. Dim fPath As String
  8. Dim sPath As String, dd() As String

  9. fPath = "C:\Documents and Settings\mvasas\Desktop\VBA\Dev\_My_Projects\"
  10. sPath = "C:\Documents and Settings\mvasas\Desktop\VBA\Dev\_My_Projects\"
  11. fDir = Dir(fPath)
  12. extFlag = 2

  13. Do While (fDir <> "")
  14. If Right(fDir, 4) = ".xls" Then
  15. extFlag = 0
  16. Else
  17. extFlag = 2
  18. End If
  19. If Right(fDir, 5) = ".xlsx" Then
  20. extFlag = 1
  21. Else
  22. extFlag = 2
  23. End If
  24. On Error Resume Next
  25. If extFlag = 2 Then
  26. fDir = Dir
  27. ElseIf extFlag = 1 Then
  28. Set wB = Workbooks.Open(fPath & fDir)
  29. csvWb = wB.Name
  30. 'Be careful here, this split will split a string into an array
  31. 'with a dot (.) delimeter. The string is the name of the workbook
  32. 'testing was performed on workbooks where the only dots were at
  33. 'the extension ie: CSVSAVERTESTFILE.xlsx. If there is a file with
  34. 'a name like, CSV.SAVER.TEST.FILE.xlsx, the file will be renamed:
  35. 'CSV.Sheet1.csv as the code takes the first String value in the
  36. 'array as the new name.
  37. dd = Split(csvWb, ".")
  38. For Each wS In wB.Sheets
  39. wS.SaveAs sPath & dd(0) & "-" & wS.Name & ".csv", xlCSV
  40. Next wS
  41. wB.Close False
  42. Set wB = Nothing
  43. fDir = Dir
  44. On Error GoTo 0
  45. End If
  46. Loop

  47. End Sub

No comments: