ExcelTip.Net留存知识帖 ---【注:附件之前被网盘供应商清空后,现已修复-现已修复-现已修复为本地下载!】
现在位置:首页 > 我的酷贴 > Excel VBA > 自定义"类似"于weeknum的函数

自定义"类似"于weeknum的函数

作者:绿色风 分类: 时间:2022-08-18 浏览:54
楼主
DJ_Soo
Q:如何找到对应的weeknum?
我使用的weeknum和Excel提供的weeknum不同,主要区别在于一年的第一周的定义:
比如我用outlook可以用工具-选项-日历选项中设置第一周的判断(如下图),但是Excel不能有这样的判断,怎么办呢?


 →
 
A:ALT+F11→插入模块→在模块中输入以下代码:
  1. Function WeekNumO(Dt As Date) As Integer
  2.     Dim Fd As Date
  3.     Dim LEd As Date
  4.     Dim Wd As Byte
  5.     Dim Yr As Integer
  6.     Yr = Year(Dt)
  7.     Fd = DateSerial(Yr, 1, 1)
  8.     LEd = DateSerial(Yr, 1, 0)
  9.     With Application
  10.         Wd = IIf((Fd - 1) Mod 7, (Fd - 1) Mod 7, 7)
  11.         If Wd <= 4 Then
  12.             WeekNumO = .RoundUp(((Dt - Fd + Wd)) / 7, 0)
  13.         Else
  14.             WeekNumO = .RoundUp(((Dt - Fd + Wd)) / 7, 0) - 1
  15.             If WeekNumO = 0 Then WeekNumO = WeekNumO(LEd)
  16.         End If
  17.     End With
  18. End Function

今天是2010-6-7,我输入=weeknumo(today())得到的是23而不是24。这样就符合我的要求了
2楼
DJ_Soo
更新,加入年份:
  1. Function WeekNumO(Dt As Date, Optional sty As String) As Long
  2.     Dim Fd As Date
  3.     Dim LEd As Date
  4.     Dim Wd As Byte
  5.     Dim Yr As Integer
  6.     Yr = Year(Dt)
  7.     Fd = DateSerial(Yr, 1, 1)       '今年第一天
  8.     LEd = DateSerial(Yr, 1, 0)      '去年最后一天
  9.     With Application
  10.         Wd = IIf((Fd - 1) Mod 7, (Fd - 1) Mod 7, 7) '周天的情况,会返回0,则改成7(weekday)
  11.         If Wd <= 4 Then                             '第一天是周四之前直接/7向上取整得到周号
  12.             WeekNumO = .RoundUp(((Dt - Fd + Wd)) / 7, 0)
  13.             If sty = "year" Then WeekNumO = Year(Fd) & Format(WeekNumO, "00")
  14.         Else
  15.             WeekNumO = .RoundUp(((Dt - Fd + Wd)) / 7, 0) - 1 '第一天是周四之后直接/7向上取整得到周号-1
  16.             If WeekNumO = 0 Then 'WeekNumO = WeekNumO(LEd)  '跨年的情况取去年年份
  17.                 If sty = "year" Then
  18.                     WeekNumO = Year(LEd) & Format(WeekNumO, "00")
  19.                 Else
  20.                     WeekNumO = WeekNumO(LEd)
  21.                 End If
  22.             Else                                            '不跨年就取今年的年份
  23.                 If sty = "year" Then
  24.                     WeekNumO = Year(Fd) & Format(WeekNumO, "00")
  25.                 End If
  26.             End If
  27.         End If
  28.     End With
  29. End Function

免责声明

有感于原ExcelTip.Net留存知识的价值及部分知识具有的时间限定性因素, 经与ExcelTip.Net站长Apolloh商议并征得其同意, 现将原属ExcelTip.Net的知识帖采集资料于本站点进行展示, 供有需要的人士查询使用,也慰缅曾经的论坛时代。 所示各个帖子的原作者如对版权有异议, 可与本人沟通提出,或于本站点留言,我们会尽快处理。 在此,感谢ExcelTip.Net站长Apolloh的支持,感谢本站点所有人**绿色风(QQ:79664738)**的支持与奉献,特此鸣谢!
------本人网名**KevinChengCW(QQ:1210618015)**原ExcelTip.Net总版主之一

评论列表
sitemap