Private Sub Workbook_BeforeSave...
MsgBox "Why"
如果 Form1 获得焦点 - MsgBox 不会出现。保存过程被取消。
请不要告诉我最终用户必须在表单外单击才能保存文件。
Form1 不是模态的。
请在表单上放置一个文本框,将光标放在其中,或者只需单击表单标题。然后按Ctrl+S,看看MsgBox有没有出现。– Alegro 49 分钟前
在这种情况下,只需将此代码粘贴到您的用户表单中。此代码根据我的其他答案稍作修改。
代码(经过试验和测试):
Private Declare Function GetKeyboardState _
Lib "user32" (pbKeyState As Byte) As Long
Private Myarray(255) As Byte
Dim Cntrl_Key As Boolean, Sletter_Key As Boolean
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
If KeyCode = 17 Then Cntrl_Key = True
If KeyCode = 83 Then Sletter_Key = True
Call ShowKey
End Sub
Private Sub RefreshKeyState(RefreshState As Boolean)
If RefreshState Then
Call GetKeyboardState(Myarray(0))
End If
End Sub
Private Sub ShowKey()
'~~> Check for Ctrl + S
If Cntrl_Key = True And Sletter_Key = True Then
'~~> Save Workbook
ActiveWorkbook.Save
Cntrl_Key = False
Sletter_Key = False
End If
End Sub
屏幕截图:
注意:这不是一个万无一失的方法,因为用户可以按下CTRL然后输入其他内容,然后按下“S”键,然后代码仍然会触发。我们可以包含一个小检查,以查看按下后CTRL按下的下一个键是否是S。如果不是,则再次将其设置为 false ... 例如
Private Declare Function GetKeyboardState _
Lib "user32" (pbKeyState As Byte) As Long
Private Myarray(255) As Byte
Dim Cntrl_Key As Boolean, Vletter_Key As Boolean
Dim OtherLetter As Boolean
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
If KeyCode = 17 Then Cntrl_Key = True
If KeyCode = 83 Then Vletter_Key = True
If KeyCode <> 83 And KeyCode <> 17 Then
OtherLetter = True
End If
Call ShowKey
End Sub
Private Sub RefreshKeyState(RefreshState As Boolean)
If RefreshState Then
Call GetKeyboardState(Myarray(0))
End If
End Sub
Private Sub ShowKey()
'~~> Check for Ctrl + S
If Cntrl_Key = True And OtherLetter = True Then
Cntrl_Key = False
ElseIf Cntrl_Key = True And Vletter_Key = True Then
'~~> Save Workbook
ActiveWorkbook.Save
Cntrl_Key = False
Vletter_Key = False
End If
End Sub