如何关闭空白Excel工作簿和宏工作簿?

时间:2014-06-11 15:58:39

标签: excel vba excel-vba

我有2个Excel工作簿,其中一个包含宏,另一个工作簿调用宏工作簿。

在主工作簿中打开事件宏工作簿将在同一个应用程序实例中打开,当工作簿关闭时我正在关闭宏工作簿,之后我编写了Appication.Quit,但这里的问题是关闭宏工作簿后一个空白的Excel雷蒙斯开放。

如何通过VBA关闭空白工作簿?

顺便说一句,我在Office 2007和2010年仅在2013年面临此问题,因此没有空白。

以下是Macro.xlsm - Module1

中的代码
Public Sub Test()
MsgBox "Test"
End Sub

Public Sub Auto_Close()
ThisWorkbook.Saved = True
End Sub

以下是Test.xlsm - Thisworkbook

中的代码
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.Workbooks("Macro.xlsm").Close
Module1.CodeFileClose
End Sub

Private Sub Workbook_Open()
Module1.CodeFileOpen
End Sub

以下是Test.xlsm - Module1

中的代码
Public Sub CodeFileOpen()
Application.Workbooks.Open ("C:\Macro.xlsm")
Application.Run "Macro.xlsm!Test"
End Sub

Public Sub CodeFileClose()
MsgBox "Before Close"
Application.Quit
End Sub

4 个答案:

答案 0 :(得分:1)

Application.Quit 

,或

thisworkbook.close

将再次触发你的workbook_beforeclose事件!!!!

所以你将循环它

在test.xlsm中,这个工作簿部分:

Private Sub Workbook_BeforeClose(Cancel As Boolean) 'if you get in here, workbook is already going to close

on error resume next 'if macro.xlsm not opened it would cause an error

thisworkbook.saved= true ' (=no save) or false(=save) or delete line if you want to be asked

with Application
    .displayalerts=false 'set to true if want to be asked before saving
    .enableevents=false 'block events from both workbooks
    .Workbooks("Macro.xlsm").Close
    .enableevents=true 'enable events from both workbooks
end with

'Module1.CodeFileClose 'will cause looping (except if you add application.enableevents=false, but then it will be the case for all excell and you wont be able to triger events, or reset it to true by code)

End Sub

答案 1 :(得分:0)

根据我的理解,您希望关闭宏工作簿以及最初打开工作簿的工作簿。

如果这是对的,为什么不在CodeFileClose()Sub中尝试以下代码:

Public Sub CodeFileClose()
    MsgBox "Before Close"
    Workbooks("Macro.xlsm").Close
End Sub

如果我错了,请提供一些有关您问题的详细信息。

答案 2 :(得分:0)

我是这样做的。诀窍是使用Application.Parent.Quit关闭应用程序的父级:

Sub Close_the_whole_excel_window()

Dim New_session_Excel as New Excel.Application

New_session_Excel.Workbooks.Open Filename:=(Path&FileName), ReadOnly:=True

New_session_Excel.Quit ' This will close the workbook and leave an extra Excel window that stays behind

New_session_Excel.Parent.Quit ' This will close the extra Excel window that stays behind

End Sub

答案 3 :(得分:0)

首先关闭父级,然后关闭应用程序,使它正常工作

ActiveWorkbook.Save
Application.DisplayAlerts = False

Excel.Parent.Quit
Application.Quit
相关问题