Skip to content

Instantly share code, notes, and snippets.

@trastle
Last active December 16, 2015 15:59
Show Gist options
  • Save trastle/5459798 to your computer and use it in GitHub Desktop.
Save trastle/5459798 to your computer and use it in GitHub Desktop.
Helping a mate who needed to convert a bunch of CSVs to XLSX files.
' Does the following:
' 1: Convert all of the CVS in the current directory to XLSX files.
' 2: Deletes the CSVs
'
' Usage:
' 1: Place this script in the directory with the CSVs.
' 2: Double click it.
' 3: Jobs a good'un
'
' Borrowing heavily from here:
' http://www.winutilis.net/html/misc/vbs/csv2xls.asp
'
' This script can be downloaded from GitHub
' https://gist.github.com/trastle/5459798
Const xlDelimited = 1
Const xlTextQualifierDoubleQuote = 1 'Double quotation mark (").
Const xlTextQualifierNone = -4142 'No delimiter.
Const xlTextQualifierSingleQuote = 2 'Single quotation mark (').
' Get the current directory
strSrcFullPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")
Set FSO = CreateObject("Scripting.FileSystemObject")
iterateOverFolder FSO.GetFolder(strSrcFullPath)
' Iterate over all CSVs in the directory
Sub iterateOverFolder(Folder)
For Each File in Folder.Files
ext = Right(File.name, 3)
If UCase(ext) = "CSV" Then
ConvertAFile(File.Path)
FSO.DeleteFile File.Path
End If
Next
End Sub
Sub convertAFile(fileName)
strSrcFullPath = fileName
strTargetDir = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")
strDelimiter = ","
objTmpArray = Split(strSrcFullPath,"\")
strSrcFileName = objTmpArray(UBound(objTmpArray))
If( Right(strTargetDir,1) <> "\" ) Then
strTargetDir = strTargetDir & "\"
End If
objTmpArray = Split(strSrcFileName,".")
strExtension = objTmpArray(UBound(objTmpArray))
strSrcFileName = Replace(strSrcFileName,"."&strExtension,"")
strXlsFile = strTargetDir &strSrcFileName &".xlsx"
Set objExl = CreateObject("Excel.Application")
objExl.Visible = False
objExl.CutCopyMode = False
objExl.Workbooks.OpenText strSrcFullPath,,,xlDelimited,xlTextQualifierDoubleQuote,,,,,,True,strDelimiter
objExl.Cells.Select
objExl.Selection.Columns.AutoFit
objExl.Range("A1").Select
objExl.ActiveWorkbook.SaveAs strXlsFile, 51
objExl.ActiveWorkbook.Close True
objExl.Application.Quit
Set objExl = Nothing
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment