Validate Inputbox entry

G

Greg Maxey

It seems like there should be a cleaner way of doing this. I want the user
to enter a valid date in a inputbox and set the value of the input box to a
string.

Sub CalcAge()
Dim pStr As String
Do Until IsDate(pStr)
pStr = InputBox("Enter the birthdate", "Birthdate")
If Not IsDate(pStr) Then
MsgBox "Please enter a valid date"
End If
Loop
'More code here.
End Sub
 
J

Jay Freedman

It seems like there should be a cleaner way of doing this. I want the user
to enter a valid date in a inputbox and set the value of the input box to a
string.

Sub CalcAge()
Dim pStr As String
Do Until IsDate(pStr)
pStr = InputBox("Enter the birthdate", "Birthdate")
If Not IsDate(pStr) Then
MsgBox "Please enter a valid date"
End If
Loop
'More code here.
End Sub

Hi Greg,

I don't think there's much improvement to be done. You can eliminate
one of the IsDate calls this way:

Sub CalcAge2()
Dim pStr As String
Do While pStr = ""
pStr = InputBox("Enter the birthdate", "Birthdate")
If pStr = "" Then Exit Sub
If Not IsDate(pStr) Then
MsgBox "Please enter a valid date"
pStr = ""
End If
Loop
'More code here.
End Sub

Also, note the "emergency exit" if the user decides to jump out of the
loop -- the only indication you get from InputBox that the user
clicked the Cancel button is that the return string is empty. Since we
grabbed that condition as meaning "go around the loop again", there's
no other way out except Ctrl+Break.
 
G

Greg Maxey

Thanks Jay.

I seems like I saw or came up with a clever way of validating a inputbox
input once before that was much simplier. Thanks for the pointing out the
emergency exit.
 

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