Only One Decimal Point In Textbox, Using Keyascii
This is want I have at the moment.
Code:
Private Sub text1_keypress(keyascii As Integer)
Select Case keyascii
Case "8", "46", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "127"
Case Else
keyascii = 0
End Select
End Sub
But I only want a maximum of one decimal Point, how do I do this?
Re: Only One Decimal Point In Textbox, Using Keyascii
Code:
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 46 Then
If InStr(1, Text1.Text, ".") > 0 Then
KeyAscii = 0
MsgBox "Multiple decimal points are not allowed.", vbOKOnly + vbInformation, "Input Error"
Exit Sub
End If
End If
End Sub
Re: Only One Decimal Point In Textbox, Using Keyascii
'you can also try something like this....
Private Sub Text1_Change()
Static strOldValue As String
If IsNumeric(Text1.Text) Then
strOldValue = Text1.Text
Else
'Text1.Text = 0
Text1.Text = strOldValue ' or a default value like 0
End If
Debug.Print Text1.Text
End Sub
Re: Only One Decimal Point In Textbox, Using Keyascii
Re: Only One Decimal Point In Textbox, Using Keyascii
Not sure why you have quotes around the KeyAscii values. Anyway, this code appears to work well:
Code:
Dim PointLook As Boolean
Private Sub Text1_Change()
If InStr(Text1.Text, Chr$(46)) = 0 Then PointLook = False
End Sub
Private Sub Text1_Keypress(KeyAscii As Integer)
Select Case KeyAscii
Case 8, 46, 127, 48 To 57
If PointLook = True And KeyAscii = 46 Then
KeyAscii = 0
ElseIf KeyAscii = 46 Then PointLook = True
End If
Case Else
KeyAscii = 0
End Select
End Sub
Note that backspace can erase the decimal, so the Text1.Change event toggles the Boolean such that if the decimal is erased, it is available once again.
Re: Only One Decimal Point In Textbox, Using Keyascii
You might also consider my NumberBox ActiveX control
Re: Only One Decimal Point In Textbox, Using Keyascii
This code will also allow the minus sign if the first charcter
Private Sub Text1_KeyPress(KeyAscii As Integer)
numbersOnly KeyAscii, Text1
End Sub
Sub numbersOnly(KeyAscii As Integer, txtBox As TextBox)
On Error GoTo e
'Allow Backspace, minus sign, Period and Enterkey
If KeyAscii <> 8 And KeyAscii <> 45 And KeyAscii <> 46 And KeyAscii <> 13 Then
If Chr(KeyAscii) < "0" Or Chr(KeyAscii) > "9" Then
KeyAscii = 0
Beep
End If
End If
If InStr(txtBox, ".") Then 'don't allow more than 1 decimal
If KeyAscii = 46 Then KeyAscii = 0
GoTo bail
End If
If Len(txtBox.Text) > 0 And KeyAscii = 45 Then 'only allow minus sign at Leftmost position
KeyAscii = 0
End If
Exit Sub
e:
MsgBox "numbersOnly" & err.number & " " & err.Description
bail:
End Sub