将Excel文件转换为CSV - 无法抑制Excel提示窗口

时间:2016-09-25 13:37:02

标签: excel powershell csv vbscript gulp

我有一个Gulp任务监视Excel文件并运行VBScript:

Gulp代码:

.pipe(shell([
    'XlsToCsv.vbs test test.xlsx test.csv'
]))

VBScript代码:

If WScript.Arguments.Count < 3 Then
    WScript.Echo "Please specify the sheet, the source, the destination files. Usage: ExcelToCsv <sheetName> <xls/xlsx source file> <csv destination file>"
    Wscript.Quit
End If

csv_format = 6

Set objFSO = CreateObject("Scripting.FileSystemObject")

src_file = objFSO.GetAbsolutePathName(Wscript.Arguments.Item(1))
dest_file = objFSO.GetAbsolutePathName(WScript.Arguments.Item(2))

Dim oExcel
Set oExcel = CreateObject("Excel.Application")

Dim oBook
Set oBook = oExcel.Workbooks.Open(src_file)

oBook.Sheets(WScript.Arguments.Item(0)).Select
oBook.SaveAs dest_file, csv_format

oBook.Close False
oExcel.Quit

除了以CSV格式重新保存文件时提示跳转,它工作正常。 比如“具有此名称的文件已存在。您要保存它吗?”

我无法在保存之前删除以前的文件,因为Gulp观察程序将触发代码执行。 oBook.Close SaveChanges = TrueoExcel.DisplayAlerts = False无效。

我需要在每次保存时默默运行此脚本。

我应该在脚本中添加什么命令?

P.S。我不介意使用任何其他脚本,但PowerShell除外 - Set-ExecutionPolicy remotesigned导致错误

  

Set-ExecutionPolicy:拒绝访问注册表项HKEY_LOCAL_MACHINE ... \ Microsoft.PowerShell'

1 个答案:

答案 0 :(得分:4)

在保存之前删除现有文件

If objFSO.FileExists(dest_file) Then objFSO.DeleteFile dest_file
oBook.SaveAs dest_file, csv_format

或设置DisplayAlerts = False以取消提示(这也会强制替换现有文件):

oExcel.DisplayAlerts = False
oBook.SaveAs dest_file, csv_format