PDA

View Full Version : [SOLVED:] Problem using keyPress command



GabrielAuger
05-19-2016, 01:03 PM
Hi,

I would like to enable the use of the minus sign (-) in a textbox of a userform. I really don't understand why the code in the attached file doesn't work.

Can someone help me?

Thanks!

SamT
05-19-2016, 04:17 PM
Please! Copy the code in the VBA editor, then in the Forum editor, click the # icon and press Ctrl+V. Do not use screenshots, the forum software resizes them to next to unread-ability.

This thread moved to the Excel Help forum until a different forum is indicated

SamT
05-19-2016, 04:22 PM
You can type a "-" into a TextBox, but it is only a character, not a mathematical operator.

Paul_Hossler
05-19-2016, 04:58 PM
I would like to enable the use of the minus sign (-) in a textbox of a userform. I really don't understand why the code in the attached file doesn't work.


Without testing anything, I'd guess it was because you have 'Or key = -' Then Exit Sub

So if a minus is entered, the 'Or' is true and the sub exits

GabrielAuger
05-20-2016, 05:09 AM
Yes I know, but I want to enable only numbers, the decimal separator, backspace and the minus sign. All works exept for the minus sign. Do you have any idea?

GabrielAuger
05-20-2016, 05:28 AM
Yes I know, but I want to enable only numbers, the decimal separator, backspace and the minus sign. All works exept for the minus sign. Do you have any idea?

Paul_Hossler
05-20-2016, 06:01 AM
See if this works

A quick Google ...

http://www.vbforums.com/showthread.php?13255-vbkeysubtract




KeyCode Constants (e.g. vbKeySubtract and vbKeyReturn)
are applicable in either KeyDown or KeyUp events but not
on a KeyPress event. You can use the ASCII code equivalent
instead...Thus a minor change in your code will be to use the ASCII code for the minus sign (45) instead of vbKeySubtract...

e.g.
Code:
Private Sub Text5_KeyPress(KeyAscii As Integer)
If Not IsNumeric(Chr(KeyAscii)) And KeyAscii <> 13 _
And KeyAscii <> 45 And KeyAscii <> 8 Then
KeyAscii = 0
End If
End Sub

GabrielAuger
05-20-2016, 06:29 AM
Thanks, work great.

GabrielAuger
05-20-2016, 06:30 AM
Yes, it is Ors. Thanks

mikerickson
05-20-2016, 06:52 AM
Yes I know, but I want to enable only numbers, the decimal separator, backspace and the minus sign. All works exept for the minus sign. Do you have any idea?

You could use a routine like this. Testing the whole entry rather than each individual character. It will allow entry of things like "3e+23" as well as the numerals that you described.


Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Dim newEntry As String

With TextBox1
newEntry = Left(.Text, .SelStart) & Chr(KeyAscii) & Mid(.Text, .SelStart + .SelLength + 1)
End With

If Not (IsNumeric(newEntry & "0")) Then
KeyAscii = 0
Beep
End If
End Sub

(If you so go the test each character route, you have to consider entries like "1.72-34" unless you want that)

GabrielAuger
05-20-2016, 07:03 AM
Good idea thanks