从Word VBA防止Excel提示

我在Word和Excel上使用VBA。 我有运行一个用户窗体的Word将自动打开一个Excel文件。 用户应该填写Excel文件中的一些数据,然后返回到Word用户窗体。 当用户完成填写Word用户窗体中的所有字段时,它将在Word上运行一些将数据从Excel复制到Word的VBA代码。 完成后,Excel文件将自动closures。 因此,我需要防止用户手动closuresExcel应用程序。

为此,我在Sub Workbook_BeforeClose中的Excel VBA中使用这些代码。 如果用户closuresExcel应用程序窗口,将显示一个消息框,询问用户是否仍在使用Word用户窗体。 代码如下:

 Private Sub Workbook_BeforeClose(Cancel As Boolean) answer = MsgBox("Are you still working with Word userform?", vbYesNo) If answer = vbYes Then Cancel = True MsgBox "This workbook should not be closed. It will be automatically closed when you finish working with Ms. Word Template Userform." Else Application.ThisWorkbook.Saved = True End If End Sub 

在Word VBA中,我有closuresExcel文件的代码:

 Sub closeExcelApp() If Not excelApp Is Nothing Then excelApp.DisplayAlerts = False excelWb.Close savechanges:=False Set excelWb = Nothing excelApp.Quit End If Set excelApp = Nothing End Sub 

当Word将VBA代码从Excel复制到Word时,将调用该Sub。 但是,调用此Sub将导致Workbook_BeforeClose调用。 同时,当我从Word VBA调用closeExcelApp ,我不想调用Workbook_BeforeClose

任何build议?

你可以禁用事件:

 Sub closeExcelApp() If Not excelApp Is Nothing Then excelApp.DisplayAlerts = False excelApp.EnableEvents = False excelWb.Close savechanges:=False Set excelWb = Nothing excelApp.Quit End If Set excelApp = Nothing End Sub 

如注释中所述,在模块的顶部添加以下代码行: Public ClosingFromWord As Boolean值,在开始代码执行时将此布尔值设置为False

在应用程序之间工作时,最简单的方法是将Word中的布尔值写入Word中的单元格中,并在Workbook_BeforeClose读取/放置此值,以避免执行该例程的整个代码。

并修改你的代码看起来像这样:

 Sub closeExcelApp() ClosingFromWord = True excelApp.Workbooks(1).Sheets(1).Cells(1,1) = ClosingFromWord If Not excelApp Is Nothing Then excelApp.DisplayAlerts = False excelWb.Close savechanges:=False Set excelWb = Nothing excelApp.Quit End If Set excelApp = Nothing ClosingFromWord = False excelApp.Workbooks(1).Sheets(1).Cells(1,1) = ClosingFromWord End Sub 

所以,当你执行closeExcelApp ,布尔值将被设置为True ,并且Workbook_BeforeClose将不会被执行,因为它将被退出If ClosingFromWord Then Exit Sub

 Private Sub Workbook_BeforeClose(Cancel As Boolean) ClosingFromWord = Workbooks(1).Sheets(1).Cells(1,1) If ClosingFromWord Then Exit Sub answer = MsgBox("Are you still working with Word userform?", vbYesNo) If answer = vbYes Then Cancel = True MsgBox "This workbook should not be closed. It will be automatically closed when you finish working with Ms. Word Template Userform." Else Application.ThisWorkbook.Saved = True End If End Sub