How to detect if a specific key was pressed? - vba

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

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/

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

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

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/

Related

How do I check if a value a user is entering in Textbox is a numeric double?

I am trying to check if a user enters a number value in a textbox, decimal places accepted. Any help is highly appreciated.
Private Sub textbox1_AfterUpdate()
If IsNumeric(textbox1.Value) = False Then
Me!textbox1.Undo
MsgBox "only numbers are allowed"
Exit Sub
End If
Exit Sub
using BeforeUpdate event:
Private Sub textbox1_BeforeUpdate(Cancel As Integer)
If IsNumeric(textbox1.Value) = False Then
MsgBox "only numbers are allowed"
Me!textbox1.Undo
Cancel = True
Exit Sub
End If
Exit Sub
My current code does not execute at all. I have also tried it in the textbox1_BeforeUpdate event. Please see code.
New Code:
Public Function IsValidKeyAscii(ByVal keyAscii As Integer, ByVal value As
String) As Boolean
IsValidKeyAscii = (keyAscii = vbKeyDot And InStr(1, value, Chr$(vbKeyDot)) =
0) Or (keyAscii >= vbKey0 And keyAscii <= vbKey9)
End Function
Private Sub textbox1_KeyDown(KeyCode As Integer, Shift As Integer)
If Not IsValidKeyAscii(KeyCode, textbox1.value) Then KeyCode = 0
End Sub
You shouldn't be using VBA for this task at all.
Just set the field format property to General number. That's the built-in way to ensure users can only enter numbers in a field.
Write a validator function (could be in its own KeyInputValidator class or module), so you can reuse this logic everywhere you need it, instead of copy/pasting it for every numeric textbox you need:
Option Explicit
Private Const vbKeyDot As Integer = 46
'#Description("returns true if specified keyAscii is a number, or if it's a dot and value doesn't already contain one")
Public Function IsValidKeyAscii(ByVal keyAscii As Integer, ByVal value As String) As Boolean
IsValidKeyAscii = (keyAscii = vbKeyDot And InStr(1, value, Chr$(vbKeyDot)) = 0) Or (keyAscii >= vbKey0 And keyAscii <= vbKey9)
End Function
Then use it in the textboxes' KeyPress event handler (assuming this is a MSForms textbox control) to determine whether or not to accept the input - since the event provides a MSForms.ReturnInteger object, that object's Value property can be set to 0 to "swallow" a keypress:
Private Sub TextBox1_KeyPress(ByVal keyAscii As MSForms.ReturnInteger)
If Not IsValidKeyAscii(keyAscii.Value, TextBox1.value) Then keyAscii.Value = 0
End Sub
That way you don't need to undo any inputs, or pop any annoying warning or message boxes: the value in the field is guaranteed to be a valid numeric value!
EDIT the above event handler signature is for a MSForms control. Looks like Access uses a different interface:
Private Sub TextBox1_KeyDown(KeyCode As Integer, Shift As Integer)
Here the KeyCode is passed ByRef, so you can alter it directly. In other words, this becomes the logic:
If Not IsValidKeyAscii(KeyCode, TextBox1.value) Then KeyCode = 0
You can try using the lost focus event:
Private Sub TextBox1_LostFocus()
Dim blnNumber As Boolean
Dim strNumber As String
strNumber = TextBox1.Value
blnNumber = IsNumeric(strNumber)
If Not blnNumber Then
Me!TextBox1.Undo
MsgBox "only numbers are allowed"
Else
'And, if you want to force a decimal.
If InStr(strNumber, ".") < 1 Then
Me!TextBox1.Undo
MsgBox "only doubles are allowed"
End If
End If
End Sub
Also, check the Textbox1 element that you have listed in access. Is it's name TextBox1? or something else?
For example, in excel it is represented like the following: =EMBED("Forms.TextBox.1","") even though the name that the code references is TextBox1.

push enter key in text boxt then go to specific cell

How to move cursor in text box with enter in text box?
Here is my code, it gives me a syntax error.
Private Sub TextBox2_Change()
Sheets("30").Range("D18") = TextBox2.Value
TextBox2.Enter Then Sheets("30").Range("E19").Select
End Sub
Instead of using the Change event, use the KeyUp event and check for the KeyCode vbKeyReturn:
Private Sub TextBox2_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = KeyCodeConstants.vbKeyReturn Then
Sheets("30").Range("E19").Select
End If
End Sub

VBA Excel Converting a KeyPress validation to a class module to be able to use it to multiple forms

I found a code online for validating user input to textbox to numeric only and restricting copy/paste. So what I wanted to do is convert it to a class module that I could use by calling it rather than putting the code to every textboxes. I already search online but they're using a different approach for validation. Appreciate it if someone could help. Here's the code.
'~~> Disable Pasting CTRL V , SHIFT + INSERT
Private Sub txtLvl_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If (Shift = 2 And KeyCode = vbKeyV) Or (Shift = 1 And KeyCode = vbKeyInsert) Then
KeyCode = 0
End If
End Sub
'~~> Preventing input of non numerics
Private Sub txtLvl_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
Case vbKey0 To vbKey9, vbKeyBack, vbKeyClear, vbKeyLeft, _
vbKeyRight, vbKeyUp, vbKeyDown, vbKeyTab
Case Else
KeyAscii = 0
Beep
End Select
End Sub
Thanks in advance.

VBA - Proceed Command with Enter

I want to make this textbox: if I type "clean" and press enter, I want it to take action like below. Is there any ways to achieve it? Here's what I tried.
Private Sub TextBox1_Change()
If TextBox1.Text = "clean" + KeyCode(13) Then
Shell "cmd /c cleanmgr.exe", vbHide
End If
End Sub
Thanks.
This is possibly what you are looking for:
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
If TextBox1.Text = "clean" Then
MsgBox "ok" 'for test
'do your stuff here!!
End If
End If
End Sub

Excel ActiveX ComboBox onClick event

I am trying to use the ActiveX ComboBox in excel. Everything works fine to the point of being populated from the drop down button click_event. But when it set the click event I find it is triggered even from keystrokes like the Arrow keys. Is this normal behavior, and if so how can I bypass this?
I am working on Excel 2007 VBA
This is the method i used to allow navigating in the combo box using keys , i will wait to see if there is a better solution.. : lastkey is a public variable
Private Sub ComboBox1_KeyDown(ByVal KeyCode As _
MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 38 Then
If ComboBox1.ListIndex <> 0 Then
lastkey = KeyCode
ComboBox1.ListIndex = ComboBox1.ListIndex - 1
KeyCode = 0
End If
ElseIf KeyCode = 40 Then
If ComboBox1.ListIndex <> ComboBox1.ListCount - 1 Then
lastkey = KeyCode
ComboBox1.ListIndex = ComboBox1.ListIndex + 1
KeyCode = 0
End If
End If
End Sub
Private Sub ComboBox1_Click()
If lastkey = 38 Or lastkey = 40 Then
Exit Sub
Else
MsgBox "click"
End If
End Sub
Yes this is normal behavior. Using the arrow keys navigates the items in the combo and hence the click event is fired.
To bypass that insert this code. This captures all the 4 arrow keys and does nothing when it is pressed. The only drawback of this method is that you will not be able to navigate using the Arrow keys anymore.
Private Sub ComboBox1_KeyDown(ByVal KeyCode As _
MSForms.ReturnInteger, ByVal Shift As Integer)
Select Case KeyCode
Case 37 To 40: KeyCode = 0
End Select
End Sub
FOLLOWUP
Dim ArKeysPressed As Boolean
Private Sub ComboBox1_Click()
If ArKeysPressed = False Then
MsgBox "Arrow key was not pressed"
'~~> Rest of Code
Else
ArKeysPressed = False
End If
End Sub
Private Sub ComboBox1_KeyDown(ByVal KeyCode As _
MSForms.ReturnInteger, ByVal Shift As Integer)
Select Case KeyCode
Case 37 To 40: ArKeysPressed = True
End Select
End Sub