How can i make the TextBox to only accept numbers?
Thanks in advance!
Printable View
How can i make the TextBox to only accept numbers?
Thanks in advance!
In a module:
Then just use:Code:Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Public Const GWL_STYLE = (-16)
Public Const ES_NUMBER = &H2000&
Public Sub SetNumber(txtNumberText As TextBox, bNumOnly As Boolean)
Dim lCurStyle As Long
Dim lNewStyle As Long
lCurStyle = GetWindowLong(txtNumberText.hwnd, GWL_STYLE)
If bNumOnly Then
lCurStyle = lCurStyle Or ES_NUMBER
Else
lCurStyle = lCurStyle And (Not ES_NUMBER)
End If
lNewStyle = SetWindowLong(txtNumberText.hwnd, GWL_STYLE, lCurStyle)
txtNumberText.Refresh
End Sub
...to set it only numbers.Code:SetNumber Text1, True
Code:Private Sub Text1_KeyPress(KeyAscii As Integer)
'allow for special characters & backspace
If Not (IsNumeric(Chr(KeyAscii))) _
And KeyAscii <> 8 Then KeyAscii = 0
If KeyAscii < 33 Then Exit Sub
End Sub
One easy way to do this, is read, what user types and check if it's numeric...
This code checks 'newest' char if textbox. This is working way (i think, didn't test). ;)Code:sub Text1_Change...
on error resume next
if IsNumeric(text1.text) = False then
if IsNumeric(Right(Text1.Text,1)) = False then
Text1.Text = Left(Text1.Text,(Len(Text1.Text)-1))
Beep
end if
end if
I think, that that API-way is powerful and easy way, and this is slow and no-so-sure way. But if you got nothing, you need to do something =)
one line baby!
Code:Private Sub Text1_KeyPress(KeyAscii As Integer)
If IsNumeric(Chr(KeyAscii)) = False Then KeyAscii = 0
End Sub
geoff, that will accept numbers, but what if you hit backspace? Nothing will happen. Use this code so you can delete as well.
Code:Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii < 33 Then Exit Sub
If Not (IsNumeric(Chr(KeyAscii))) Then KeyAscii = 0
End Sub
Code:Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii > 33 Then If Not (Chr(KeyAscii) Like "#") Then KeyAscii = 0
End Sub
Matthew! C'mon! Who the hell uses backspace?? I dont make mistakes so I don't use it!
:rolleyes:
Picky picky picky!
LOL!
to much of my thought has been going into my code coloring prog...
cant think on such simple levels anymore!! LOL
here...
Code:Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 8 Or KeyAscii = 32 Then Exit Sub Else If IsNumeric(Chr(KeyAscii)) = False Then KeyAscii = 0
End Sub
Thanks a lot everyone! :D