Our project for today was to design a program that calculates target heart rates for a user given their birthdate and heart rate. Now, we were supposed to learn to use SELECT CASE and If/Then statements are were not allowed use of any robust date functions (Like Cdate() or IsDate()). We had to break the user interface (UI) into three sections for Day, Month and Year rather than allow single entry in MM/DD/YYYY format.
Because we had three fields with which to deal, I had to write this nutty bit of code to validate for correct Day/Month combos, accept both YY and YYYY format and check for leap years.
'validate year data sTemp = Val(txtYear.Text) 'store year data in temporary string If sTemp <= 0 Then Call MsgBox("Please enter Year as a number.", , "In the zone - Year") txtYear.BackColor = &H8080FF txtYear.SetFocus Exit Sub ElseIf IsNumeric(sTemp) Then If Len(sTemp) = 4 Then iYear = sTemp ElseIf Len(sTemp) = 2 Then If Val(sTemp) < 30 Then iYear = 20 & sTemp Else iYear = 19 & sTemp 'the previous was a ridiculously involved validation of the date, so both YY and YYYY formats work End If End If End If 'validate month data iMonth = Val(txtMonth.Text) 'store Month as numeric data If iMonth < 1 Or iMonth > 12 Then 'validate Month value for numeric data between 1 and 12 Call MsgBox("Please enter Month as a number between 1 and 12.", , "In the zone - Month") txtMonth.BackColor = &H8080FF 'highlight field to fix txtMonth.SetFocus Exit Sub End If 'set var that will determine valid day/month combos Select Case iMonth Case 4, 6, 9, 11 iValidDay = 30 Case 1, 3, 5, 7, 8, 10, 12 iValidDay = 31 Case 2 And iYear Mod 4 = 0 And iYear Mod 100 <> 0 iValidDay = 29 Case 2 And iYear Mod 4 <> 0 iValidDay = 28 End Select 'Validate & store day iDay = Val(txtDay.Text) 'store day as numeric data If iDay < 1 Or iDay > iValidDay Then Call MsgBox("Please enter Day as a number between 1 and " & iValidDay & ".", , "In the zone - Day") txtDay.BackColor = &H8080FF 'highlight incorrect field txtDay.SetFocus 'change cursor focus Exit Sub End If 'Calculate user age If iDay <= Day(Date) And iMonth <= Month(Date) Then iAge = Year(Date) - iYear 'calculate age Else iAge = Year(Date) - iYear - 1 End If ' display age (used to test age formula) End Sub
Now, it works. I'm willing to bet it's really clunky given that this is my second day coding in VB6.
Were we allowed to use the nifty date functions, the entire code above would have been as follows.
If IsDate(txtBirthDate.Text) Then 'validate if data entered is a real date iBirthdate = txtBirthDate 'store Birthdate in iBirthDate Else Call MsgBox("Please enter birthdate in Month Day, YYYY format.",,"Target Heart Rate - Date error") 'pop an error if date is invalid End If iBirthDateConverted = CDate(iBirthDate) 'convert data to date expression.. to be safe...
Not sure if that's exactly right, suffice that the code would be 10% as long as it is.
Still having fun in class though.