BeforeClose Before不会closures我的Excel表单VBA

所以我一直在试图把一个小的Excel工作表,它有一个条目login。 所以每当表格被closures,名称,date和时间被添加。

所以基本上我有三个macros运行,我只会提两个。 主macros会问我是否要closures表单,我将不得不回答是或否。 这工作正常。 如果我按是主macros将调用一个子macros,这将要求我input一个string。 如果这个Inputbox是空的或者入口被取消了,我想让main子停止运行并取消Close进程。 这似乎不工作。 在代码中的错误似乎很清楚,但我不知道如何防止它,并find一个更好的解决scheme。 如果你能帮我想出一个解决scheme,我会非常感激。

这行代码似乎是问题:

If Cancel_Button_LOG = False Then Cancel = True 

在这里,我将添加两个macros的压缩版本

 Public Sub Add_Entry_to_Log() Dim i As Integer Dim response As Variant Cancel_Button_LOG = True response = InputBox("Please enter your Name", "Name") If response <> "" Then Else Cancel_Button_LOG = False MsgBox "Please enter your name", vbExclamation + vbOKOnly, "Name" End If Worksheets("Log").Protect "secret" ThisWorkbook.Save End Sub 

现在我想要使用Cancel_Button_logvariables来取消主要的sub:

  Dim answer As Variant answer = MsgBox("Are your sure you want to close the workbook?", vbYesNo) Cancel = False Select Case answer Case Is = vbYes Worksheets("Log").Unprotect "secret" Call Test Call Add_Entry_to_Log If Cancel_Button_LOG = False Then Cancel = True Worksheets("Log").Protect "secret" Case Is = vbNo Cancel = True End Select ThisWorkbook.Save End Sub 

我想你是以最复杂的方式做到这一点。 如果我正确理解了你的要求,你可以用你的ThisWorkbook模块中的所有代码replace成这样:

 Const WB_LOG As String = "Log" '// name of sheet that the log is in Private Sub Workbook_BeforeClose(Cancel As Boolean) If MsgBox("Do you really want to close the workbook?", vbYesNo) = vbYes Then With Sheets(WB_LOG) .Range("A" & .Rows.Count).End(xlUp).Offset(1, 0).Resize(1, 2).Value = Array(Environ$("USERNAME"), Now) End With ThisWorkbook.Save Else Cancel = True End If End Sub Private Sub Workbook_Open() With Sheets(WB_LOG) .Protect Password:="secret", UserInterfaceOnly:=True .Range("A1:B1").Value = Array("USERNAME", "TIMESTAMP") End With End Sub 

这将不需要用户手动插入他们的名字(假设他们的系统用户名就足够了),并且否定每次使用UserInterfaceOnly选项UserInterfaceOnly需要解除工作表的保护。


*如果用户希望这样做,并知道如何 – %USERNAME%环境variables可以被窜改,然而有人在文本框中键入他们的名字更容易伪造…