XL2000: Sample Macro to Determine If a Year Is a Leap Year (266672)



The information in this article applies to:

  • Microsoft Excel 2000

This article was previously published under Q266672

SUMMARY

In Microsoft Excel, you can determine whether a date occurs during a leap year by using a Microsoft Visual Basic for Applications macro.

MORE INFORMATION

Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements.

Sample Macro to Determine If a Year is a Leap Year

For more information about how to use the sample code in this article, click the article number below to view the article in the Microsoft Knowledge Base:

212536 OFF2000: How to Run Sample Code from Knowledge Base Articles

  1. Close and save any open workbooks, and then open a new workbook.
  2. Type a date in cell A1, such as 1/12/1736.
  3. Start the Visual Basic Editor (press ALT+F11).
  4. On the Insert menu, click Module.
  5. Type or paste the following procedure in the Code window for Module1:
    Sub LeapYearTest()
        Dim x As Boolean
        Dim z As Integer
    
          z = Year(Range("A1").Value)
          x = False
          If z Mod 4 = 0 And z Mod 100 > 0 Then x = True
          If z Mod 400 = 0 Then x = True
    
          If x Then
             MsgBox z & (" is a Leap Year")
          Else
             MsgBox z & (" is not a Leap Year")
          End If
       End Sub
    					
  6. On the File menu, click Close and Return to Microsoft Excel.
  7. On the Tools menu, point to Macro, and then click Macros. In the Macros dialog box, click LeapYearTest, and then click Run.
NOTE: If you use this macro with the date 1/1/1900, the macro returns the year 1899 instead. This only happens with a date of January 1, 1900. For additional information about this issue, click the article number below to view the article in the Microsoft Knowledge Base:

214326 XL2000: Excel Incorrectly Assumes 1900 Is a Leap Year

REFERENCES

For additional information about leap years, click the article number below to view the article in the Microsoft Knowledge Base:

214019 XL2000: Method to Determine Whether a Year Is a Leap Year


Modification Type:MinorLast Reviewed:10/11/2006
Keywords:kbdtacode kbhowto KB266672