![]() |
![]() |
|
|||||||
| Excel Questions All Excel/VBA questions - formulas, macros, pivot tables, general help, etc. Please post to this forum in English only. |
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
New Member
Join Date: Apr 2002
Posts: 2
|
What's wrong with this code? :
Private Sub mathsnumber_Change() If mathsnumber.Text > 5 Then Beep MsgBox "Invalid Entry!" mathsnumber.Text = "5" End If End Sub The code is for a text box which is part of of a user form and is meant to only allow the user to input a number between 1-5 (the default value is 5). Otherwise a msg box comes up with an error msg, and changes the text box value back to 5. It seems to work, except when the text box's contents are deleted by the user and then gives a VB error: runtime eror "13" type mismatch |
|
|
|
|
|
#2 |
|
MrExcel MVP
Join Date: Feb 2002
Location: Sydney, Australia
Posts: 2,908
|
Hi,
The reason you're getting the Type mismatch is this:- As soon as the user clears the textbox the 'text' will not be numeric and this line will fail:- If mathsnumber.Text > 5 Then You're comparing a string (or a null) with a number. You need to check that the entry is numeric first by doing something like this. You also need to check if the value is not text i.e. Code:
Private Sub mathsnumber_Change()
If IsNumeric(mathsnumber.Text) Then
If mathsnumber.Text > 5 Then
Beep
MsgBox "Invalid Entry!"
mathsnumber.Text = 5
End If
Else
If Len(mathsnumber.Text) > 0 Then mathsnumber.Text = ""
End If
End Sub
Dan |
|
|
|
|
|
#3 |
|
New Member
Join Date: Apr 2002
Posts: 2
|
mucho thanks
|
|
|
|
![]() |
| Bookmarks |
| Thread Tools | |
| Display Modes | |
|
|