VBScript在保存和关闭Excel工作簿之前结束

时间:2019-01-22 19:46:26

标签: excel vbscript

我有一个非常基本的VBScript,我希望能够从Task Scheduler调用它来打开Excel文档,刷新所有文档,然后保存并关闭它。 我一直在玩我在网上找到的各种代码(因为我对此很陌生),因此可以打开并刷新所有代码,但是VBScript在保存和/或关闭工作簿之前先关闭。

我尝试添加“ WScript.Sleep”(具有不同的时间)以及DoEvents以允许Excel完成,但是该脚本在保存和关闭工作簿之前仍然关闭。

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = 
objExcel.Workbooks.Open("\\llfs01\ReportHub(Shoals)\Sales\Daily 
Reports\F&I Daily Reports\CIT Report.xlsm")

objExcel.Application.Visible = True
objExcel.DisplayAlerts = False
objExcel.AlertBeforeOverwriting = False
objWorkbook.WorkSheets(1).Activate
objWorkbook.RefreshAll 'Refresh everything
objWorkbook.DoEvents 'Let Excel finish
WScript.Sleep 20000
objExcel.ActiveWorkbook.Save
DoEvents
objExcel.ActiveWorkbook.Close

我需要代码来打开工作簿(在PC处于锁定状态且无人值守的情况下),刷新工作簿中的所有数据,保存并关闭工作簿。

1 个答案:

答案 0 :(得分:0)

您可以设置变量= objExcel.ActiveWorkbook.BuiltinDocumentProperties("Last Save Time"),然后循环Do Events直到objExcel.ActiveWorkbook.BuiltinDocumentProperties("Last Save Time") > variable

Dim s

s = objExcel.ActiveWorkbook.BuiltinDocumentProperties("Last Save Time")

objExcel.ActiveWorkbook.Save
Do Until objExcel.ActiveWorkbook.BuiltinDocumentProperties("Last Save Time") > s
    DoEvents
Loop
objExcel.ActiveWorkbook.Close

编辑:

根据OP的评论添加到原始代码正文中

Dim s
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("\\llfs01\ReportHub(Shoals)\Sales\Daily 
Reports\F&I Daily Reports\CIT Report.xlsm")

s = objExcel.ActiveWorkbook.BuiltinDocumentProperties("Last Save Time")

objExcel.Application.Visible = True
objExcel.DisplayAlerts = False
objExcel.AlertBeforeOverwriting = False
objWorkbook.WorkSheets(1).Activate
objWorkbook.RefreshAll 'Refresh everything

objExcel.ActiveWorkbook.Save
Do Until objExcel.ActiveWorkbook.BuiltinDocumentProperties("Last Save Time") > s
    DoEvents
Loop
objExcel.ActiveWorkbook.Close