2016-07-26 17 views
1

我發現一個VBScript將Excel文件轉換爲CSV文件,並將其修改爲我的需要。我處理的文件通常在受保護的視圖,因此我有以下代碼:VBScript Excel到CSV轉換器非常慢,受保護視圖更慢

format = 6 

Set objFSO = CreateObject("Scripting.FileSystemObject") 

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

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

oExcel.DisplayAlerts = False 
oExcel.ProtectedViewWindows.Open(src_file) 
If oExcel.ProtectedViewWindows.Count > 0 Then 
    oExcel.ActiveProtectedViewWindow.Edit 
End If 
Dim oBook 
Set oBook = oExcel.Workbooks.Open(src_file) 

oBook.Worksheets(5).Activate 

oBook.SaveAs dest_file, format 

oBook.Close False 
oExcel.DisplayAlerts = True 
oExcel.Quit 

該腳本將刪除Excel文件的保護視圖並保存當前工作表中選擇一個CSV文件。如果我第一次運行它,大約需要25-27秒才能將4個受保護的視圖excel文件轉換爲csv文件。當我第二次運行它時,excel文件不再處於保護視圖中,我得到了類似的結果。我很好奇,看看我除去受保護的視圖檢查會發生什麼,所以我做了以下內容:

format = 6 

Set objFSO = CreateObject("Scripting.FileSystemObject") 

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

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

oExcel.DisplayAlerts = False 

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

oBook.Worksheets(5).Activate 

oBook.SaveAs dest_file, format 

oExcel.AutomationSecurity = lSecurity 

oBook.Close False 
oExcel.DisplayAlerts = True 
oExcel.Quit 

現在我無法打開受保護的這個腳本Excel文件,但如果Excel文件是不受保護它比以前的腳本更快地轉換它們。現在不在保護視圖中的4個excel文件平均需要14秒才能轉換爲csv文件。我已經跑了很多次,以確保每次都獲得相同的結果。

爲什麼檢查受保護的視圖會導致腳本花費更長的時間?有什麼方法可以讓它跑得更快嗎?另外,還有沒有其他的辦法來通過命令行將Excel文件轉換爲CSV?我也試過Powershell,它比VBScript更快!但我無法讓它適用於受保護的視圖文件。我應該提到,我正在Qt 5.6中通過QProcess運行這些腳本。感謝任何幫助

回答

2

在第一個你打開文件2次!一個用於oExcel.ProtectedViewsWindow,另一個用於oExcel.Workbooks

嘗試這樣的事情(未測試):

format = 6 

Set objFSO = CreateObject("Scripting.FileSystemObject") 

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

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

oExcel.DisplayAlerts = False 
oExcel.ProtectedViewWindows.Open(src_file) 
Dim oBook 
If oExcel.ProtectedViewWindows.Count > 0 Then 
    Set oBook = oExcel.ActiveProtectedViewWindow.Edit 
Else 
    Set oBook = oExcel.ActiveWorkbook 
End If 

oBook.Worksheets(5).Activate 

oBook.SaveAs dest_file, format 

oBook.Close False 
oExcel.DisplayAlerts = True 
oExcel.Quit 
+0

你是一個生命的救星。有用!現在大約需要17秒來轉換4個excel文件,這是一個很大的改進。但是,是否有可能讓它更快?在我的GUI程序中,我根據excel文件的數量運行此腳本(在這種情況下腳本運行了4次)。你認爲它會更快,如果我只是運行一次腳本並迭代excel文件?這樣我就不必創建很多Excel.Applications。再次感謝 – Dillydill123

+0

對不起,我不太瞭解VB。但我認爲這是可能的,可能與'Excel.Application'的'Windows'屬性有關。 –

+0

沒問題。我設法弄明白了,它確實減少了約4秒的時間。 – Dillydill123