View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Harald Staff Harald Staff is offline
external usenet poster
 
Posts: 292
Default Textbox validation

Hi

I always do this in Keydown and Keypress, like this (for decimal number
entries):

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal
Shift As Integer)
If Shift = 2 Then 'Ctrl
If KeyCode = 86 Then 'V
'paste. Decide what to do, or/and
'discard like this:
KeyCode = 0
End If
End If
End Sub

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
With TextBox1
Select Case KeyAscii
Case 45
'minus, must be first
If .SelStart 0 Then KeyAscii = 0
Case 46 'decimal separator, one only
If InStr(.Text, ".") 0 Then KeyAscii = 0
Case 48 To 57
'numbers, ok
Case Else
KeyAscii = 0
End Select
End With
End Sub

It takes some coding, but has proven itself very robust and reliable.

HTH. Best wishes Harald

"phreud " skrev i melding
...
I need to add validation to all my textboxes in my userform. The
userform has textboxes connected to a worksheet (using controlsource)
on which I create some graphs. I'll be looking at validating correct
ranges, positive numbers, string lengths and so on.

I've been looking at a couple of solutions. Range.validation.add and
the BeforeUpdate event, but none seem to work as I want.

I've also found something called Micorsoft Masked Edit Control, but it
seems my licence doesn't include it.

How can I catch invalid input before it generates errors in my code? As
it it now, users can input values that create division by zero and so
on.

Thanks in advance!

On a side note: If a number is entered that creates a division by 0,
the formula in my cell gets deleted. Why is that?


---
Message posted from http://www.ExcelForum.com/