Excel VBA :周数
Excel VBA : week numbers
我正在使用 Excel VBA,如何使用?
输入月份和年份以及 return 本月的所有周数。
输入日期并获取该日期的周数。
从日期中获取星期
Input a date and get the week number for this date.
代码
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
结果
获取月份的所有星期
Input month and year and return all week numbers for this month.
代码
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
结果
说明
- 代码首先获取一个月中的所有日期
intDaysInMonth
,因此在 2017 年 2 月它将输出 28
.
- 使用
MonthYearDay
循环每个月的每一天,并用当天的星期 Application.WorksheetFunction.WeekNum(MonthYearDay)
. 填充数组 MyArray
- 然后创建集合
arr(i)
以输出数组MyArray
中的唯一值
On future requests, post what you have tried. I am answering it because i couldn't find a suitable answer for: Input month and year and return all week numbers for this month.
我正在使用 Excel VBA,如何使用?
输入月份和年份以及 return 本月的所有周数。
输入日期并获取该日期的周数。
从日期中获取星期
Input a date and get the week number for this date.
代码
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
结果
获取月份的所有星期
Input month and year and return all week numbers for this month.
代码
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
结果
说明
- 代码首先获取一个月中的所有日期
intDaysInMonth
,因此在 2017 年 2 月它将输出28
. - 使用
MonthYearDay
循环每个月的每一天,并用当天的星期Application.WorksheetFunction.WeekNum(MonthYearDay)
. 填充数组 - 然后创建集合
arr(i)
以输出数组MyArray
中的唯一值
MyArray
On future requests, post what you have tried. I am answering it because i couldn't find a suitable answer for: Input month and year and return all week numbers for this month.