簡體   English   中英

如何關閉空白Excel工作簿以及Macro工作簿?

[英]How to close blank excel workbook along with Macro workbook?

我有2個Excel工作簿,一個包含宏,另一個工作簿稱為宏工作簿。

在主工作簿打開事件中,宏工作簿將在同一應用程序實例中打開,當工作簿關閉時,我正在關閉宏工作簿,然后編寫了Appication.Quit,但是這里的問題是在關閉宏工作簿后打開了一個空白的Excel Remians。

如何通過VBA關閉空白工作簿?

順便說一句,我僅在2013年就在Office 2007和2010中面臨此問題,沒有空白的Excel。

以下是Macro.xlsm - Module1的代碼

Public Sub Test()
MsgBox "Test"
End Sub

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

以下是Test.xlsm - Thisworkbook的代碼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
Application.Quit 

, 要么

thisworkbook.close

會再次觸發您的workbook_beforeclose事件!!!!

所以你會循環

在test.xlsm的thisworkbook部分中:

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

據我了解,您想關閉宏工作簿以及最初打開工作簿的工作簿。

如果是正確的話,為什么不嘗試在CodeFileClose()中嘗試以下代碼:

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

如果我錯了,請提供更多有關您的問題的詳細信息。

這是我的方法。 訣竅是使用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

我通過先關閉父級然后關閉應用程序來使其工作:

ActiveWorkbook.Save
Application.DisplayAlerts = False

Excel.Parent.Quit
Application.Quit

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM