如何检测一个特定的键是否被按下?

我想知道是否有一种方法来检测是否按下特定的键(如backspace)。 这是我拍摄的:

Private Sub SomeTextBox_Change() If len(Me.SomeTextBox.Value) = 3 and KEYPRESSED is NOT BACKSPACE Then <.......Code Here> Else <.......Code Here> End if End Sub 

您应该使用KeyPress事件而不是Change事件:

 Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) If Len(Me.SomeTextBox.Value) = 3 And KeyAscii <> 8 Then 'Backspace has keycode = 8. <.......Code Here> Else <.......Code Here> End If End Sub 

您可以在这里find完整的键码列表: http : //www.asciitable.com/

 Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) If KeyCode.Value = vbKeyF1 Then MsgBox "F1 is pressed" End If End Sub 

本示例将“InsertProc”分配给键序列CTRL + PLUS SIGN,并将“SpecialPrintProc”分配给键序列SHIFT + CTRL + RIGHT ARROW。

 Application.OnKey "^{+}", "InsertProc" Application.OnKey "+^{RIGHT}","SpecialPrintProc" 

有关更多示例和信息,请访问: https : //msdn.microsoft.com/en-us/library/office/aa195807%28v=office.11​​%29.aspx

您应该使用KeyPress事件:

 Private Sub SomeTextBox_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) If Len(Me.SomeTextBox.Value) = 3 And KeyAscii <> vbKeyBack Then '<.......Code Here> Else '<.......Code Here> End If End Sub 

您可以使用KeyAscii = 0来取消input的密钥!

在这里查找所有Ascii值的列表http://www.asciitable.com/