0

I'm using Excel VBA, How can I ?

  • Input month and year and return all week numbers for this month.

  • Input a date and get the week number for this date.

Community
  • 1
  • 1
Mohammed Zegui
  • 83
  • 2
  • 11

1 Answers1

2

To get week from Date

Input a date and get the week number for this date.

Code

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

Result

Result1

To get all weeks on month

Input month and year and return all week numbers for this month.

Code

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

Result

Result2

Explanation

  • The code first get all the days on a month with intDaysInMonth, so on February of 2017 it will output 28.
  • Loop on each day of the month with MonthYearDay and populate the array MyArray with the week of that day Application.WorksheetFunction.WeekNum(MonthYearDay).
  • Then create the collection arr(i) to output the unique values from the array 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.

danieltakeshi
  • 887
  • 9
  • 37
  • Thank you sir, I'm not familiar to Stackoverflow guidelines. I will definitely consider what you said. – Mohammed Zegui Nov 20 '17 at 20:44
  • @MohammedZegui Please take the [tour](https://stackoverflow.com/tour), read [How to Ask](https://stackoverflow.com/help/how-to-ask) and [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Please verify [Why is “Can someone help me?” not an actual question?](http://meta.stackoverflow.com/q/284236). – danieltakeshi Nov 21 '17 at 10:29
  • Well I get the following error for the second code : Runtime Error 5 : Invalid procedure call or argument. When I click debug it highlights the following line : MyArray(j) = Application.WorksheetFunction.WeekNum(MonthYearDay) – Mohammed Zegui Nov 23 '17 at 17:49
  • Are you declaring everything? And are you sure that the Date is inputed as Date? – danieltakeshi Nov 24 '17 at 10:38