[英]VBA: Workbook.Close loop
I have the following portion of the code for a given active worksheet: 对于给定的活动工作表,我具有以下代码部分:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim sh As Worksheet
Dim myMessage
If ActiveSheet.Range("I5").Value > 0 Then
MsgBox "Some cells are empty" _
& Chr(13) & Chr(13) & "Please, fill in the empty cells to proceed", _
vbExclamation + vbOKOnly, "ERROR!"
Cancel = True
Else
ThisWorkbook.Unprotect ("123")
Worksheets("Instructions").Visible = True
Worksheets("Instructions").Activate
For Each sh In Worksheets
If sh.Name <> "Instructions" Then
sh.Visible = xlVeryHidden
End If
Next sh
ThisWorkbook.Protect ("123")
myMessage = MsgBox("Do you want to save and close this file?", vbQuestion + vbYesNo, "Workbook 1")
If myMessage = vbYes Then
Application.DisplayFormulaBar = True
ThisWorkbook.Close True
ElseIf myMessage = vbNo Then
Cancel = True
Else
'nothing
End If
End If
End Sub
In general, upon pressing the close button on the workbook itself, the idea is to check a given cell of a given active worksheet for a non-zero value. 通常,在按下工作簿本身上的关闭按钮时,其想法是检查给定活动工作表的给定单元格是否为非零值。 If it is non-zero, the user has to fill in certain empty cells first and the workbook is not closed.
如果它不为零,则用户必须先填写某些空单元格,并且工作簿不会关闭。 Alternatively, the "Instruction" worksheet is activated and the user receives a message box of what to do next (by doing this, instead of simply no msgbox and sticking with the usual system "SAVE/NO" prompt, is that I want to eliminate the possibility of a user pressing the "No" button, which will lead to no save being made).
或者,激活“指令”工作表,用户会收到一个下一步要执行的消息框(通过执行此操作,而不是简单地没有msgbox并坚持使用通常的系统“ SAVE / NO”提示,是我要消除用户按下“否”按钮的可能性,这将导致无法进行保存)。 The only problem I have is the one-time loop I get when a user selects "Yes" answer: the same message box re-appears (apparently, because the procedure goes through the code line again!).
我唯一的问题是用户选择“是”答案时得到的一次性循环:再次出现相同的消息框(显然是因为该过程再次通过了代码行!)。 I would appreciate if you could suggest me the way I could avoid this loop.
如果您能建议我避免这种循环的方式,我将不胜感激。
If you are not going to allow the user not to save then why not force a save. 如果您不打算允许用户不保存,那么为什么不强制保存。 You can replace the entire message box prompt section:
您可以替换整个消息框提示部分:
myMessage = MsgBox("Do you want to save and close this file?", vbQuestion + vbYesNo, "Workbook 1")
If myMessage = vbYes Then
Application.DisplayFormulaBar = True
ThisWorkbook.Close True
ElseIf myMessage = vbNo Then
Cancel = True
Else
'nothing
End If
with 与
ThisWorkbook.Save
This will force the save and close the workbook. 这将强制保存并关闭工作簿。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.