VBA学习(23):处理日期和时间

下面的过程和函数代码用于处理日期和时间。

指定年的第一个星期一

下面的函数返回指定年的第一个星期一的日期。

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)

 技术交流,软件开发,微信如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xwLink1996

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值