vba转换周数(和年)到目前为止?

时间:2017-02-16 10:47:18

标签: excel vba excel-vba formula

我在Cell C13中有周数,在Cell C14中有

我使用以下公式将其转换为该周的星期四号码的日期:

=DATE(C14,1,-6)-WEEKDAY(DATE(C14,1,3))+C13*7

我怎么能用VBA做同样的事情?

3 个答案:

答案 0 :(得分:5)

对于特定年份,您可以这样做:

DateAdd("ww", WeekNumber - 1, DateSerial(2017, 1, 5))

并测试它:

Debug.Print Format(DateAdd("ww", WeekNumber - 1, DateSerial(YearNumber, 1, 5)), "ddd d MMM yy")

如果其他人正在研究这个问题并且不想要一个星期四或者不想在2017年工作

  1. 更改5以满足您的需求!

  2. 或使用以下函数GetDayFromWeekNumber

  3. 测试代码:

    Sub test()
        Debug.Print Format(GetDayFromWeekNumber(2017, 1, 4), "ddd d MMM yyyy")
    End Sub
    

    泛型函数GetDayFromWeekNumber

    Public Function GetDayFromWeekNumber(InYear As Integer, _
                    WeekNumber As Integer, _
                    Optional DayInWeek1Monday7Sunday As Integer = 1) As Date
        Dim i As Integer: i = 1
        If DayInWeek1Monday7Sunday < 1 Or DayInWeek1Monday7Sunday > 7 Then
            MsgBox "Please input between 1 and 7 for the argument :" & vbCrLf & _
                    "DayInWeek1Monday7Sunday!", vbOKOnly + vbCritical
            'Function will return 30/12/1899 if you don't use a good DayInWeek1Monday7Sunday
            Exit Function
        Else
        End If
    
        Do While Weekday(DateSerial(InYear, 1, i), vbMonday) <> DayInWeek1Monday7Sunday
            i = i + 1
        Loop
    
        GetDayFromWeekNumber = DateAdd("ww", WeekNumber - 1, DateSerial(InYear, 1, i))
    End Function
    

答案 1 :(得分:1)

一切正常,请记住一周的第一天是星期天:

Function fnDateFromWeek(ByVal iYear As Integer, ByVal iWeek As Integer, ByVal iWeekDday As Integer)

        fnDateFromWeek = DateSerial(iYear, 1, ((iWeek - 1) * 7) + iWeekDday - Weekday(DateSerial(iYear, 1, 1)) + 1)

End Function

您必须通过哪一天作为第三个参数。星期四是第5天。这些人的信用:http://www.dreamincode.net/forums/topic/111464-calculate-date-from-year-weeknr-and-daynumber/

答案 2 :(得分:1)

作为附加选项,对于那些使用ISO周数系统的人来说,一年中的第1周是包含四天的一年中的第一周(或包括该日历年的第一个星期四和第一天的那一周)本周是星期天。

  • DOW是表示星期几的可选参数。它将默认为星期四,因为我们使用的是ISO周数系统,所以应该始终属于当前年份。
Option Explicit
Function WNtoDate(WN As Long, YR As Long, Optional DOW As Long = 5) As Date
    'DOW:  1=SUN, 2=MON, etc
    Dim DY1 As Date
    Dim Wk1DT1 As Date
    Dim I As Long

DY1 = DateSerial(YR, 1, 1)
'Use ISO weeknumber system
I = DatePart("ww", DY1, vbSunday, vbFirstFourDays)

'Sunday of Week 1
Wk1DT1 = DateAdd("d", -Weekday(DY1), DY1 + 1 + IIf(I > 1, 7, 0))

WNtoDate = DateAdd("ww", WN - 1, Wk1DT1) + DOW - 1

End Function