Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

VBA UDF for list of MM.YYYY (months) between two dates

I am trying to list the dates between two given months: a) 1/1/2021; b) 6/1/2021 in format:
01.2021; 02.2021; 03.2021; 04.2021; 05.2021; 06.2021
I was able to find and use this UDF:

Function MONTHRANGE(startDate As Date, endDate As Date, _
                                Optional Delim As String = "; ", _
                                Optional dFormat As String = "MM.YYYY") As String
                                
MONTHRANGE = Join(Evaluate("TRANSPOSE(TEXT(ROW(" & CLng(startDate) & ":" & CLng(endDate) & ")," & Chr(34) & dFormat & Chr(34) & "))"), Delim)
End Function

The output of this is repeated dates (for each day of the month) in the format I want – how can I return just the unique values (one – per month)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Something like the following gets the job done:

Option Explicit

Private Sub Test()
   Debug.Print GetMonths(CDate("1/1/2021"), CDate("6/1/2021"))
End Sub

Private Function GetMonths(ByVal StartDate As Date, ByVal EndDate As Date) As String
   Do While StartDate <= EndDate
      GetMonths = GetMonths & Format(Month(StartDate), "00") & "." & Year(StartDate) & "; "
      StartDate = DateAdd("m", 1, StartDate)
   Loop
   
   GetMonths = Left(GetMonths, Len(GetMonths) - 2)
End Function
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading