问题
I have a scheduled task that launches a vb script which in turn runs a macro within excel. Everything runs fine (as in I get the results I want), however, the scheduled task remains 'running' and therefore doesn't start again the next morning. The VB Script is as follows:
Option Explicit
Dim xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\MyPath\My File.xlsm", 0, True)
xlApp.Run "myMacro"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Quit
The end of the Macro (all the preceding code work and saves my csv output as required):
Workbooks("My File.xlsm").Activate
Worksheets("Outputs").Select
'ActiveWorkbook.Save
'ActiveWorkbook.Close - this line cause vbs to fail after creating my csv
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
How do I terminate the VB Script to stop the scheduled task from running?
回答1:
Unfortunately as you realized:
Workbooks("My File.xlsm").Activate
Worksheets("Outputs").Select
'ActiveWorkbook.Save
'ActiveWorkbook.Close - this line cause vbs to fail after creating my csv
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Will give you an error due to the fact that the xlBook object is attempting to close the already closed workbook. I believe that if you update VBScript to:
Option Explicit
Dim xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\MyPath\My File.xlsm", 0, True)
xlApp.Run "myMacro"
'xlBook.Close Remove this line
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Quit
and add back the ActiveWorkbook.Save and ActiveWorkbook.Close lines, you VBScript & Excel application should close correctly.
来源:https://stackoverflow.com/questions/31402313/vbs-doesnt-stop-running