VBS Doesn't stop running

蓝咒 提交于 2019-12-11 16:28:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!