excelperfect 本文中的代码来自于www.cpearson.com,特辑录于此,方便在需要时参考。 下面的过程和函数代码用于处理日期和时间。 指定年的第一个星期一 下面的函数返回指定年的第一个星期一的日期。 Public Function YearStart(WhichYear As Integer) As Date Dim WeekDay As Integer Dim NewYear As Date NewYear =DateSerial(WhichYear, 1, 1) WeekDay =(NewYear - 2) Mod 7 If WeekDay < 4 Then YearStart = NewYear - WeekDay Else YearStart = NewYear - WeekDay + 7 End If End Function 注意,本文下面的程序将会使用这个函数。 指定周数的星期一 下面的函数返回指定年指定周的星期一的日期。 Public Function WeekStart(WhichWeek As Integer,WhichYear As Integer) As Date WeekStart= YearStart(WhichYear) + ((WhichWeek - 1) * 7) End Function 判断是否闰年 下面的函数在指定年是闰年时返回TRUE,否则返回FALSE。 Public Function IsLeapYear(Y As Integer) IsLeapYear = Month(DateSerial(Y, 2, 29)) = 2 End Function 某星期第几天的日期 下面的函数返回指定年月的指定周的指定天的日期,例如,Y=2021,M=6,N=2,DOW=3,将返回2021年6月第2周第3天的日期,即2021年6月8日。默认情况下,星期日=1,星期六=7。 Public Function NthDayOfWeek(Y As Integer, M As Integer, N As Integer, DOW As Integer) As Date NthDayOfWeek = DateSerial(Y, M, (8 - WeekDay(DateSerial(Y, M, 1), (DOW +1) Mod 8)) + ((N - 1) * 7)) End Function 计算年龄 下面的函数计算年龄,其中Date1代表出生日期。 Function Age(Date1 As Date, Date2 As Date) As String Dim Y As Integer Dim M As Integer Dim D As Integer Dim Temp1 As Date Temp1 =DateSerial(Year(Date2), Month(Date1), Day(Date1)) Y =Year(Date2) - Year(Date1) + (Temp1 > Date2) M =Month(Date2) - Month(Date1) - (12 * (Temp1 > Date2)) D =Day(Date2) - Day(Date1) If D <0 Then M = M- 1 D =Day(DateSerial(Year(Date2), Month(Date2) + 1, 0)) + D + 1 End If Age = Y& '年'& M & '月'& D & '日' End Function 使用Find方法查找日期 由于Excel是以系列号数值来保存日期的,因此使用Find方法查找日期需要一些技巧。例如,要查找工作表中输入的日期“1977-6-20”,可以使用语句: Set FoundCell =Cells.Find(What:=DateValue('1977-6-20'), LookIn:=xlFormulas) 在编程中,往往要使用VBA代码来处理日期,上述代码可供类似情形参考。 欢迎到知识星球:完美Excel社群,进行技术交流和提问,获取更多电子资料。
|
|
来自: hercules028 > 《VBA》