我在Word和Excel上使用VBA。我让Word运行一个userform,它将自动打开一个Excel文件。用户应填写Excel文件中的一些数据,然后返回Word用户表单。当用户完成填写Word userform中的所有字段时,它将在Word上运行一些VBA代码,将数据从Excel复制到Word。完成后,Excel文件将自动关闭。因此,我需要阻止用户手动关闭Excel应用程序。
为了做到这一点,我在Sub Workbook_BeforeClose
中的Excel VBA中使用这些代码。如果用户关闭Excel应用程序窗口,它将显示一个消息框,询问用户是否仍在使用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中,我有代码关闭Excel文件:
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调用此Workbook_BeforeClose
子时,我不希望调用closeExcelApp
。
有什么建议吗?
答案 0 :(得分:2)
你可以禁用事件:
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
答案 1 :(得分:1)
如评论中所述,在模块顶部添加此行:Public ClosingFromWord As Boolean
并在开始执行代码时将此布尔值设置为 False 。
当您在应用程序之间工作时,最简单的方法是在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