[RESOLVED] Get The Number Of The Month From Its Name
I know that I can get the number of a month by feeding VB's built in MonthName function the month number
vb Code:
'returns November
Msgbox MonthName(11)
However, I need to the number of the month based on its name, and I could not find anything that would give me that.
So, I wrote this function (I have the names of all 12 months in a dropdown combo).
vb Code:
Private Function GetMonthNumber(pstrMonthName As String) As Integer
Dim i As Integer
ReDim Months(1 To 12)
ReDim MonthNumber(1 To 12)
Months = Array("January", "February", "March", "April", "May", "June", "July", _
"August", "September", "October", "November", "December")
MonthNumber = Array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12")
For i = 0 To 11
If cboMonths.Text = Months(i) Then
GetMonthNumber = MonthNumber(i)
Exit For
End If
Next
End Function
'and to get the number
Private Sub cboMonths_Click()
Dim iMonNum As Integer
iMonNum = GetMonthNumber(cboMonths.Text)
MsgBox iMonNum
End Sub
Works just fine but I can't help feeling I'm overlooking something.
Am I having a senior moment? There is an easier way of doing this, right?
Re: Get The Number Of The Month From Its Name
Your solution can be made to be multi-regional aware, but isn't as written.
The following isn't either, unless the month names are already regional aware. But is far easier I think
Code:
GetMonthNumber = Month(CDate("1/March/2000"))
Code:
GetMonthNumber = Month(CDate("March/1/2000"))
Re: Get The Number Of The Month From Its Name
Regional awareness is not an issue. This app is going to be used by one company in Michigan that formats all dates as mm/dd/yyyy.
I knew there had to be a better way.
Thanks!
Re: [RESOLVED] Get The Number Of The Month From Its Name
Depending on the requirements you might also use something like:
Code:
Function MonthNum(ByVal MonthName As String) As Integer
MonthNum = InStr("JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC", _
UCase$(Left$(MonthName, 3)))
If MonthNum > 0 Then MonthNum = (MonthNum - 1) \ 3 + 1
End Function
Re: [RESOLVED] Get The Number Of The Month From Its Name
^^ Oops, excluded a couple of months, but the logic is very valid
Re: [RESOLVED] Get The Number Of The Month From Its Name
Funny!
Next time I'll copy and paste instead of retyping. :eek2:
Re: [RESOLVED] Get The Number Of The Month From Its Name
Or pehaps;
Code:
Function MonthName2MonthNumber(Month As String) As Long
Dim i As Long
For i = 1 To 12
If UCase$(Month) = UCase$(MonthName(i)) Or UCase(Month) = UCase$(MonthName$(i, True)) Then
MonthName2MonthNumber = i
Exit For
End If
Next
End Function