微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

WeekNum VBA函数不会在特定计算机上输出该值

如何解决WeekNum VBA函数不会在特定计算机上输出该值

我一直在寻找答案,但是失败了。 我编写了以下代码,该代码基本上在表中添加了新行,并在新行的第一个单元格中添加了当前星期数:

Set table = Workbooks("EMEA Day 2 Chasing Audit Master Report.xlsm").Worksheets("Team Stats").ListObjects.Item("TableLilla")
Set oLastrowStats = Workbooks("EMEA Day 2 Chasing Audit Master Report.xlsm").Worksheets("Team Stats").ListObjects("TableLilla").ListRows.Add
Worksheets("Team Stats").ListObjects("TableLilla").ListColumns(1).DataBodyRange(oLastrowStats.Index,1).Value = "W" & WorksheetFunction.WeekNum(Now,vbMonday)

奇怪的部分从这里开始:该代码在2台计算机上都能正常工作,但在第三台计算机上却没有。在第3台计算机上,添加了新行,但第3条代码行未插入星期数。 我很确定它与这款特定的笔记本电脑有关,但是不知道在哪里寻找解决方案。我没有注意到Excel设置中的任何重大差异。我还检查了Win10的区域和日期设置,它们与我的笔记本上的相同。

您是否有办法解决这个问题?

谢谢!

解决方法

尝试使用返回ISO 8601周号(和年份)的函数:

' Constants.

    Public Const MaxWeekValue           As Integer = 53
    Public Const MinWeekValue           As Integer = 1
    Public Const MaxMonthValue          As Integer = 12
    Public Const MinMonthValue          As Integer = 1


' Returns the ISO 8601 week of a date.
' The related ISO year is returned by ref.
'
' 2016-01-06. Gustav Brock,Cactus Data ApS,CPH.
'
Public Function Week( _
    ByVal Date1 As Date,_
    Optional ByRef IsoYear As Integer) _
    As Integer

    Dim Month       As Integer
    Dim Interval    As String
    Dim Result      As Integer
    
    Interval = "ww"
    
    Month = VBA.Month(Date1)
    ' Initially,set the ISO year to the calendar year.
    IsoYear = VBA.Year(Date1)
    
    Result = DatePart(Interval,Date1,vbMonday,vbFirstFourDays)
    If Result = MaxWeekValue Then
        If DatePart(Interval,DateAdd(Interval,1,Date1),vbFirstFourDays) = MinWeekValue Then
            ' OK. The next week is the first week of the following year.
        Else
            ' This is really the first week of the next ISO year.
            ' Correct for DatePart bug.
            Result = MinWeekValue
        End If
    End If
        
    ' Adjust year where week number belongs to next or previous year.
    If Month = MinMonthValue Then
        If Result >= MaxWeekValue - 1 Then
            ' This is an early date of January belonging to the last week of the previous ISO year.
            IsoYear = IsoYear - 1
        End If
    ElseIf Month = MaxMonthValue Then
        If Result = MinWeekValue Then
            ' This is a late date of December belonging to the first week of the next ISO year.
            IsoYear = IsoYear + 1
        End If
    End If
    
    ' IsoYear is returned by reference.
    Week = Result
        
End Function

赞:

Worksheets("Team Stats").ListObjects("TableLilla").ListColumns(1).DataBodyRange(oLastrowStats.Index,1).Value = "W" & Week(Date)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。