ascii validation question

S

SimonBianchi

I have created the following code to only allow numeric values (an
decimal point) into TextBox1.

Private Sub Textbox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
Case Asc("0") To Asc("99")
Case Asc(".")
If InStr(1, TextBox1.Text, ".") > 0 Then
KeyAscii = 0
End If
Case Else
KeyAscii = 0
End Select
End Sub
The problem is this allow the entry of the decimal point alone. Thi
causes a '#VALUE' error in the target cell which in turn causes th
code to halt and bring up the debug form.
How do I modify this code so that if the user attempts to enter th
decimal point without a trailing number the value gets turned to Null
 
D

Dave Peterson

How about adding another check?

If TextBox1.Text = "" Then
KeyAscii = 0
End If

In the case asc(".") portion.

And watch that Asc("99"). I bet you meant asc("9").

====

But I don't think I'd stop this. But right before I was gonna use that value in
the textbox, I'd prefix it with a 0.

So if the user wanted to hit .5, they could.
I'd just stick a 0 in front (0.5) before processing.

Maybe even format the number on the way out:

Option Explicit
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
With Me.TextBox1
.Text = Format("0" & .Text, "0.000")
End With
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top