View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
Harald Staff[_5_] Harald Staff[_5_] is offline
external usenet poster
 
Posts: 47
Default Userform Date validation

Hi David

In my opinion users should never be bothered with proper input formats and annoying messageboxes.

The code below formats and validate all common date inputs and converts to the desired format without noise and interruptions. In
addition to all date entries that regional settings recognize, you can use
Jan 12
and 4 to 8 digit non-delimited numbers (in european ddmmyyyy order) like
1201
120195
12011995

Here's the code, I use it all the time in my projects. Edit/remove the last age check part, it's a demo for you only:

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Dim iDay As Integer
Dim iMonth As Integer
Dim iYear As Integer
Dim dtDate As Date

With TextBox1
If Val(.Text) = 1000000 Then
iDay = Int(Val(.Text) / 1000000)
iMonth = Int(Val(.Text) / 10000) Mod 100
iYear = Val(.Text) Mod 10000
dtDate = DateSerial(iYear, iMonth, iDay)
.Text = Format$(dtDate, "dd/mm/yyyy")
ElseIf Val(.Text) 10000 Then
iDay = Int(Val(.Text) / 10000)
iMonth = Int(Val(.Text) / 100) Mod 100
iYear = Val(.Text) Mod 100
If iYear 30 Then
iYear = iYear + 1900
Else
iYear = iYear + 2000
End If
dtDate = DateSerial(iYear, iMonth, iDay)
.Text = Format$(dtDate, "dd/mm/yyyy")
ElseIf Val(.Text) 100 Then
iDay = Int(Val(.Text) / 100)
iMonth = Val(.Text) Mod 100
iYear = Year(Date)
dtDate = DateSerial(iYear, iMonth, iDay)
.Text = Format$(dtDate, "dd/mm/yyyy")
Else
If IsDate(.Text) = False Then
.Text = ""
Else
dtDate = DateValue(.Text)
If dtDate < 10 Then
.Text = ""
Else
.Text = Format$(dtDate, "dd/mm/yyyy")
End If
End If
End If
End With
'edit / remove from he
If dtDate 1000 Then
Select Case Year(Date) - Year(dtDate)
Case 0 To 13
'replace with proper actions:
MsgBox "too young"
Case 80 To 999
MsgBox "too old"
Case Else
End Select
End If
End Sub
--
HTH. Best wishes Harald
Excel MVP

Followup to newsgroup only please.

"David Goodall" skrev i melding ...
Hi,
I'm currently developing a userform which has a text box that prompts the
user for a date of birth. I would like to validate the input as a correct
date of birth. ie not born before 1900 and in correct dd/mm/yyyy format.

I've had a look at the the isdate function but I'm not sure if it can handle
the British date format.

Any help would be greatly appreciated.

David