Function problem

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I created the following function from various VBA functions. When I am
expecting to retrieve the value of December from the function, but it keeps
saying LastMonth is Null when I set my system date to January. This is
isolated to the month of January only.

Public Function LastMonth()
LastMonth = MonthName(Month(Now()) - 1)
End Function
Can anyone help with this abberation? Thanks!
 
Steve said:
Can anyone help with this abberation?

Public Function LastMonth() As String
Dim mon As Integer

mon = Month(Date) - 1
If (mon = 0) Then
mon = 12
End If
LastMonth = MonthName(mon)
End Function
 
Steve said:
I created the following function from various VBA functions. When I am
expecting to retrieve the value of December from the function, but it keeps
saying LastMonth is Null when I set my system date to January. This is
isolated to the month of January only.

Public Function LastMonth()
LastMonth = MonthName(Month(Now()) - 1)
End Function
Can anyone help with this abberation? Thanks!


Not an abberation, a bug in your logic.

Subtracting 1 from a date is subtracting 1 day. If the date
is Jan 1, then Month(Now) is 1 and 1 - 1 = 0, which is not a
month number.

Try something more like:

Format(DateSerial(2000, Month(Date) - 1, 1), "mmmm")

Note that, in this case, the year doesn't matter.
Technically, it should be Year(Date), but it's easier for me
to type some year number instead. Your call.
 
Just to be different <g>

Public Function LastMonth()
LastMonth = MonthName(Month(DateAdd("m", -1, Date())))
End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top