Skip to content

Instantly share code, notes, and snippets.

@hutch120
Last active July 18, 2020 23:43
Show Gist options
  • Save hutch120/f2eb947dd79301c4cc3fe430e2b13f4b to your computer and use it in GitHub Desktop.
Save hutch120/f2eb947dd79301c4cc3fe430e2b13f4b to your computer and use it in GitHub Desktop.
Save Excel worksheet as CSV
'
' This VBS script opens an MS Excel Workbook, sets the active sheet, and saves that sheet to CSV.
'
' Usage:
' cscript //nologo saveascsv.vbs "source.xls" "worksheetname" "output.csv"
' cscript //nologo saveascsv.vbs "c:\temp\SaveAsCSV\Book1.xlsx" "Sheet2" "c:\temp\SaveAsCSV\output.csv"
'
if WScript.Arguments.Count < 3 Then
' One WScript.Echo in case user doesnt put cscript //nologo and would otherwise have to press enter a bunch of times.
WScript.Echo "Usage:" & vbCRLF & _
" cscript //nologo " & Wscript.ScriptName & " ""source.xls"" ""worksheetname"" ""output.csv""" & vbCRLF & _
"" & vbCRLF & _
" e.g." & vbCRLF & _
" cscript //nologo " & Wscript.ScriptName & " ""c:\temp\test.xls"" ""sheet2"" ""test-sheet2.csv"""
' Quit with error.
Wscript.Quit 1
End If
source = Wscript.Arguments.Item(0)
worksheetname = Wscript.Arguments.Item(1)
output = Wscript.Arguments.Item(2)
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
' Do not prompt to overwrite, just do it.
oExcel.DisplayAlerts = False
Dim oBook
Set oBook = oExcel.Workbooks.Open(source)
' Set the current worksheet
oBook.Worksheets(worksheetname).Activate
' Set the format to save as. Formats here: https://msdn.microsoft.com/en-us/library/office/ff198017.aspx
xlCSV = 6
' Save the current sheet as CSV
oBook.SaveAs output, xlCSV
' Close the various objects.
oBook.Close False
oExcel.Quit
' Quit with no error
WScript.Quit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment