Excel VBA:周数

时间:2017-11-20 12:23:40

标签: excel-vba week-number vba excel

我正在使用Excel VBA,我该怎么办?

  • 输入月份和年份,并返回本月的所有周数。

  • 输入日期并获取此日期的周数。

1 个答案:

答案 0 :(得分:1)

从日期

获得一周
  

输入日期并获取此日期的周数。

代码

Sub WeekDate()
    Dim InputDate As Date
    Dim week As Long

    InputDate = Now 'Change to desired date/cell
    week = Application.WorksheetFunction.WeekNum(InputDate)
    Debug.Print week
End Sub

结果

Result1

按月计算所有周

  

输入月份和年份,并返回本月的所有周数。

代码

Sub WeeksInMonth()
    Dim MonthYear As String, txt As String
    Dim InputDate As Date, MonthYearDay As Date
    Dim i As Long, intDaysInMonth As Long, j As Long
    Dim MyArray As Variant
    Dim arr As New Collection, a
    ReDim MyArray(0 To 31)
    j = 0
    InputDate = Now
    MonthYear = Month(InputDate) & "/" & Year(InputDate)
    intDaysInMonth = Day(DateSerial(Year(MonthYear), Month(MonthYear) + 1, 0))
    For i = 1 To intDaysInMonth
        MonthYearDay = DateSerial(Year(InputDate), Month(InputDate), i)
        MyArray(j) = Application.WorksheetFunction.WeekNum(MonthYearDay)
        j = j + 1
    Next i

    ReDim Preserve MyArray(0 To j - 1)
    On Error Resume Next
    For Each a In MyArray
        arr.Add a, CStr(a)
    Next

    For i = 1 To arr.Count
        Debug.Print arr(i)
    Next
End Sub

结果

Result2

解释

  • 代码首先获得intDaysInMonth一个月的所有日期,因此2017年2月将输出28
  • 使用MonthYearDay在每月的每一天循环,并使用当天MyArray填充数组Application.WorksheetFunction.WeekNum(MonthYearDay)
  • 然后创建集合arr(i)以从数组MyArray
  • 输出唯一值
  

在将来的请求中,发布您尝试过的内容。我正在回答它,因为我无法找到合适的答案:输入月份和年份并返回本月的所有周数。