XTreme Logo

If you appreciate these tips, please consider a small donation:

General Tip - Novice

One way to determine whether a specific year is a leap year...

Courtesy of Marshall Ellis

Periodiodically on the popular VB newsgroup comp.lang.basic.visual.misc a discussion arises on how to determine whether a given year is a leap year.  It can be done using formulas, but VB is already equipped to do the work for you with the IsDate function.


Steps for this example:
On a standard form draw a textbox, Text1, and a command button, Command1.
In the Click event of the command button place the following code:

Private Sub Command1_Click()
    Dim
iYear as Integer
    Dim dFeb29
    If Text1.Text = "" Then
       MsgBox "Please enter a year to evaluate"
       Text1.SetFocus
    End If
    iYear = Val(Text1.Text)
    dFeb29 = "2/29/" & iYear
    If IsDate(dFeb29) Then
       MsgBox iYear & " is a leap year"
    Else
       MsgBox iYear & " is not a leap year"
    End If
End Sub


You're just throwing February 29 of the year you want to evaluate at the IsDate function and if it's valid, it's a leap year. I thought it was fairly elegant and it required no math. IsDate does it for you.


[ Back To The Top ]

Contact: web@xtremecomp.com
All contents copyright XTreme Computing unless noted otherwise.