如何检测是否按下了特定键?

时间:2015-11-26 14:19:22

标签: excel vba excel-vba events userform

我想知道是否有办法检测是否按下了特定键(如退格键)。这就是我的目标:

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

4 个答案:

答案 0 :(得分:7)

您应该使用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

您可以在此处找到完整的密钥代码列表:http://www.asciitable.com/

答案 1 :(得分:5)

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

答案 2 :(得分:4)

此示例将“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

答案 3 :(得分:4)

您应该使用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取消输入的密钥!

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