How to detect if a specific key was pressed?

≡放荡痞女 提交于 2020-07-20 17:28:52

问题


I'm wondering is there a way to detect if a specific key (like backspace) was pressed. This is what I'm shooting for:

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

回答1:


You should use KeyPress event instead of Change event:

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

Full list of keycodes you can find here: http://www.asciitable.com/




回答2:


This example assigns "InsertProc" to the key sequence CTRL+PLUS SIGN and assigns "SpecialPrintProc" to the key sequence SHIFT+CTRL+RIGHT ARROW.

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

for more examples and infos go on : https://msdn.microsoft.com/en-us/library/office/aa195807%28v=office.11%29.aspx




回答3:


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



回答4:


You should use KeyPress event instead :

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

And you can use KeyAscii = 0 to cancel the key that was entered!

Find a list of all Ascii values here http://www.asciitable.com/



来源:https://stackoverflow.com/questions/33940931/how-to-detect-if-a-specific-key-was-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!