在另一个工作簿上运行宏后出现错误

时间:2018-08-09 15:36:21

标签: excel vba

我正在尝试运行远程宏,但是在关闭工作簿时出现错误“ 关闭工作簿类的方法失败”。我需要更改什么?

Sub RunRemoteMacro()
    Dim xlApp, xlWbk

    On Error GoTo errHandler

    Set xlApp = CreateObject("Excel.Application")
    Set xlWbk = xlApp.Workbooks.Open("anotherworkbook.xlsm", , True)

    xlApp.Application.Visible = True

    xlApp.Application.Run "testmacro"

    xlApp.DisplayAlerts = False

    ''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' ERROR: Close method of Workbook class failed
    ''''''''''''''''''''''''''''''''''''''''''''''''''''
    xlWbk.Close False

exitHandler:
    xlApp.Application.Quit

    Set xlWkb = Nothing
    Set xlApp = Nothing

    Exit Sub

errHandler:
    Debug.Print Now() & ": RunRemoteMacro - " & Err.Description

    On Error GoTo 0
    Resume exitHandler
End Sub

关于, 艾里奥·费尔南德斯(Elio Fernandes)

1 个答案:

答案 0 :(得分:0)

我刚刚找到一种正确关闭的方法。请参阅 exitHandler 中的代码。

Sub RunRemoteMacro()
    Dim xlApp, xlWbk

    On Error GoTo errHandler

    Set xlApp = CreateObject("Excel.Application")
    Set xlWbk = xlApp.Workbooks.Open("anotherworkbook.xlsm", , True)

    xlApp.Application.Visible = True

    xlApp.Application.Run "testmacro"

    xlApp.DisplayAlerts = False   

exitHandler:
    ' Close Workbook
    xlWbk.Close False
    Set xlWkb = Nothing

    ' Close application
    xlApp.Application.Quit
    Set xlApp = Nothing

    Exit Sub

errHandler:
    Debug.Print Now() & ": RunRemoteMacro - " & Err.Description

    On Error GoTo 0
    Resume exitHandler
End Sub