vba - 防止关闭工作簿

标签 vba excel excel-2010

ABC.xls具有宏的文件。现在,宏有一个子程序,当我按 Ctrl + M 时就会调用它。 。 此子将打开一个打开文件对话框,用户可以在其中选择 CSV文件。所以基本上,这个宏是用来处理和保存的CSV文件。 下面是按 Ctrl + M 时调用的代码。

Sub runProperChangeSubroutine()             ' Assigned to shortcut key CTRL + M.
    file_name = ActiveWorkbook.Name         ' Gets the file name.
    Application.Run file_name & "!ChangeSub"
End Sub

当用户关闭工作簿时,我必须测试像 CSV 中的每一行这样的条件。有一个终止字符串。如果该终止字符串不是 目前,我应该向用户弹出一个消息框并阻止工作簿关闭。 所以我做了以下...

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim improperRowNumber As Integer
    Dim BlnEventState As Boolean
    improperRowNumber = returnImproperRow()

    BlnEventState = Application.EnableEvents
    Application.EnableEvents = True

    If improperRowNumber <> -1 Then
        Cancel = True
        MsgBox "The row number " & improperRowNumber & " is not ending with '@/#'. Please correct the row before closing."
    Else
        Call saveCSV
    End If
    Application.EnableEvents = BlnEventState
End Sub

单击关闭(右上角的 X 标记,关闭 workboox。我没有关闭 Excel。)按钮时,我可以看到消息框,但 workboox 关闭。如果该行未正确结束,我希望用户进行一些编辑。 请提出建议。

编辑: 由于上面的代码不起作用,我使用了 ThisWorkbook.Saved = False消息框后如下所示...

If improperRowNumber <> -1 Then
    MsgBox "The row number " & improperRowNumber & " is not ending with '@/#'. Please correct the row before closing."
    Application.DisplayAlerts = False
    ThisWorkbook.Saved = False
    Cancel = False
Else

现在它显示“Do you want to save the changes.... ”消息框。如果我点击Cancel消息框上的按钮,工作簿未关闭。

有没有办法自定义消息框文本或按钮或隐藏此Save消息框?

最佳答案

如果您必须监视除包含宏的工作簿之外的工作簿的关闭,您可以从启用宏的工作簿中拦截应用程序级事件,如下所示:

在 ThisWorkbook 后面添加(或改编)此代码:

Option Explicit

Private m_CloseHelper As CloseHelper

Private Sub Workbook_Open()
    Set m_CloseHelper = New CloseHelper
End Sub

添加一个名为 CloseHelper 的新类模块:

Option Explicit

Private WithEvents m_App As Excel.Application

Private Sub Class_Initialize()
    Set m_App = Excel.Application
End Sub

Private Sub Class_Terminate()
    Set m_App = Nothing
End Sub

Private Sub m_App_WorkbookBeforeClose(ByVal Wb As Workbook, Cancel As Boolean)
    'Logic goes here, e.g. the code below will prevent the user from closing
    'any workbook other than this one, for as long as this workbook is open.
    If Not Wb Is ThisWorkbook Then
        Cancel = True
        MsgBox "Hello from m_App_WorkbookBeforeClose"
    End If
End Sub

重要的关键字是 WithEvents,其原理是现在可以在 CloseHelper 类中对 Excel 应用程序引发的事件进行编码。

您可以在这里找到一篇更深入的文章:Application Events

关于vba - 防止关闭工作簿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46682869/

相关文章:

vba - Windows API WH_MOUSE hook 在模态模式下在 VBA 用户窗体上成功,但在无模式模式下失败

excel - 将两个vba代码合二为一

string - 使用 VBA 将可变文本字符串(时间戳)插入单元格

excel - 编辑超链接 Excel 2010 宏

vba - 如何从主窗体内部引用子窗体中对象的事件

vba - Excel-VBA .Range ("NamedRange").Row 返回不同的行然后范围所在的位置

MySQL ODBC 在 Excel VBA 中将小数显示为空

excel - 使用 Python 3.5 解析所有 Excel 公式的最快方法

excel - if 语句在字符串数据 : Excel 上无法正常工作

vba - Excel - 从不同工作表和超链接上的单元格中提取数据