Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last day of month

Tags:

vba

ms-access

I want to get the last day of the month.

This is my code. If I want to debug it and compile it to the database it says it has an error in the syntax.

Public Function GetNowLast() As Date
    Dim asdfh As Date
    asdfh = DateValue("1." _
      & IIf(Month(Date) + 1) > 12, Month(Date) + 1 - 12, Month(Date) + 1) _
      &"."&IIf(Month(Date)+1)>12 , Year(Date)+1,Year(Date))
    asdf = DateAdd("d", -1, asdf)
    GetNowLast = asdf
End Function
like image 887
linuxman Avatar asked Oct 13 '15 19:10

linuxman


2 Answers

GD Linuxman,

Let's focus on obtaining the result...:-)

See also: here

The comment by @Scott Craner is spot on ! Though strictly speaking there is no need to use the formatting. (Assuming you want to work with the 'Date' object)

To achieve what you want, setup the function as per below:

Function GetNowLast() as Date

    dYear = Year(Now)
    dMonth = Month(Now)

    getDate = DateSerial(dYear, dMonth + 1, 0)

    GetNowLast = getDate

End Function

You can call the function in your code as:

Sub findLastDayOfMonth()

    lastDay = GetNowLast()

End Sub

Alternatively, and neater is likely:

Function GetNowLast(inputDate as Date) as Date

    dYear = Year(inputDate)
    dMonth = Month(inputDate)

    getDate = DateSerial(dYear, dMonth + 1, 0)

    GetNowLast = getDate

End Function

You can call that function and pass it an input parameter.

Sub findLastDayOfMonth()

lastDay = GetNowLast(Now()) 'Or any other date you would like to know the last day of the month of.

End Sub

See also this neat solution by @KekuSemau

like image 197
mtholen Avatar answered Oct 20 '22 16:10

mtholen


Sub Worksheet_SelectionChange(ByVal Target As Range)

   Dim d1 As String

   Set Rng = Range("A2")
   d1 = Range("a2").Value2 'put a date in A2 Formatted as date(cell format)

   Dim years
   Dim months
   Dim end_month
   years = year(d1)
   months = month(d1)

   end_month = Day(DateSerial(years, months + 1, 1 - 1)) 'add one month and subtract one day from the first day of that month

   MsgBox CStr(end_month), vbOKOnly, "Last day of the month"


End Sub
like image 23
Bill Avatar answered Oct 20 '22 18:10

Bill