暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

VBA代码库12:处理日期和时间

完美Excel 2021-06-29
394

学习Excel技术,关注微信公众号:

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=2021M=6N=2DOW=3,将返回20216月第2周第3天的日期,即202168日。默认情况下,星期日=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代码来处理日期,上述代码可供类似情形参考。

undefined
欢迎在下面留言,完善本文内容,让更多的人学到更完美的知识。

欢迎到知识星球:完美Excel社群,进行技术交流和提问,获取更多电子资料。

文章转载自完美Excel,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论