【发布时间】:2017-10-11 07:59:26
【问题描述】:
有ABC.xls 文件有宏。现在,宏有一个 sub,当我按下 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 标记,关闭工作簿。我没有关闭 excel。)按钮,我可以看到消息框,但工作簿关闭。如果行没有正确结束,我希望用户进行一些编辑。 请提出建议。
编辑:
由于上面的代码不起作用,我在消息框后面使用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 消息框?
【问题讨论】:
-
您应该无法在 Workbook_BeforeClose 中使用 Cancel = True 关闭工作簿。也许你在子程序不正确的行号中有类似 EnableEvents = False 的东西?
-
不,EnableEvents 语句不存在于不正确的RowNumber 子中。还有其他可能吗?
-
@MarcinSzalenec 禁用应用程序事件,msgbox 不会显示...但 OP 的处理程序显然正在运行。
-
FWIW 我似乎也无法取消关闭。谢谢,现在我会花几个小时研究 wtf 的进展,哈哈
-
如果我在这里错了,请纠正我,但是既然您成功地可以检测到没有正确结尾的行('@/#'),为什么您的代码不能将它自己添加到该行?
标签: vba excel excel-2010