![](/img/trans.png)
[英]VBA Excel: call a macro on close but not from the Workbook_BeforeClose function?
[英]BeforeClose will not close my Excel-Sheet VBA
所以我一直在尝试整理一个Excel表格,其中有一个条目登录。 因此,无论何时关闭工作表,都会添加名称,日期和时间。
所以基本上我有三个宏运行,我只提两个。 主宏将询问我是否要关闭工作表,我将不得不回答是或否。 这很好用。 如果我按是,主宏将调用子宏,这将要求我输入一个字符串。 如果此Inputbox为空或条目被取消,我希望main sub停止运行并取消Close进程。 这似乎不起作用。 我的代码中的错误似乎很清楚,但我不知道如何防止它并找到更好的解决方案。 如果你能帮我提出解决方案,我会非常感激。
这行代码似乎是问题所在:
If Cancel_Button_LOG = False Then Cancel = True
在这里,我将添加两个宏的压缩版本
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_log
变量来取消Cancel_Button_log
:
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
模块中的所有代码:
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
选项而无需取消保护工作表。
*如果用户希望这样做,并且知道如何操作,则%USERNAME%
等环境变量可能会被伪造 - 但是,如果有人在文本框中输入其名称,则更容易伪造...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.