关闭在其他函数中创建的Excel应用程序

时间:2017-08-30 07:07:41

标签: excel-vba vbscript vba excel

我在一个.vbs文件中有两个函数:

Function OpenTarget(ByVal reviewPeriod)
    ' check if file exists
    Dim FSO
    Set FSO = CreateObject("Scripting.FileSystemObject")

    If fso.FileExists("FILE_" & reviewPeriod) Then
        ' the target file is created for the first time for the given reviewPeriod, hence open the template
        Set objExcel_target                       = CreateObject("Excel.Application")
        objExcel_target.Application.Visible       = True
        objExcel_target.Application.DisplayAlerts = False
        Set OpenTarget                            = objExcel_target.Workbooks.Open("FILE_" & reviewPeriod)
    Else
        ' the target file is created for the first time for the given reviewPeriod, hence open the template
        Set objExcel_target                       = CreateObject("Excel.Application")
        objExcel_target.Application.Visible       = True
        objExcel_target.Application.DisplayAlerts = False
        Set OpenTarget                            = objExcel_target.Workbooks.Open("FILE_TEMPLATE")
    End If
End Function

Function CloseTarget(target, reviewPeriod)
    ' Save and close workbook
    target.SaveAs "Path_To_Another_File"
    target.Close (False)

    objExcel_target.Application.Quit
End Function

现在我想在第三个函数中使用这两个函数,它位于第二个.vbs文件中。脚本此时失败:

objExcel_target.Application.Quit

我理解CloseTarget()不知道objExcel_target但是我怎样才能最终使用CloseTarget函数关闭应用程序?

1 个答案:

答案 0 :(得分:3)

关闭工作簿后,您将无法再访问其属性。在关闭之前从工作簿中获取应用程序:

Function CloseTarget(target, reviewPeriod)
    Set xl = target.Application

    ' Save and close workbook
    target.SaveAs "Path_To_Another_File"
    target.Close (False)

    xl.Quit
End Function

您无法使用objExcel_target,因为它似乎是函数OpenTarget()中的局部变量。