I’m trying to get the following function to work:
Private Function FirstOfMonth(MonthsAgo As Integer) As Date
FirstOfMonth = DateSerial(Year(Now()), Month(Now() - MonthsAgo), 1)
End Function
I’m passing in a value as follows:
FirstOfMonth(4)
The aim of the function is to return the date for the first of the month a number of ‘MonthsAgo’.
However, whenever I run it it tells me that I have a Type Mismatch.
I’m new to programming, so if there’s anyone that can point me in the right direction as to where I’m going wrong, I’d be very grateful. It’s slowing me down solving a fairly simple problem.
I think what you meant to be doing was:
However, even this won’t work. Consider the case where the month is January (1). In that scenario you will end up with a Date of
2012/-3/1which is obviously complete nonsense!You will instead need to use the DateAdd function:
So your entire function looks like