Home » excel » Excel VBA – How do I find the smallest and largest keys in a dictionary

Excel VBA – How do I find the smallest and largest keys in a dictionary

Posted by: admin April 23, 2020 Leave a comment

Questions:

I created a dictionary to grab unique date values as keys, with an integer item, like so:
-Key, Item
-4/27/2017, 1
-5/4/2017, 56
-5/31/2017, 103

I want to create a title that says something like “Report for MINDATE through MAXDATE“, so I need to be able to grab the smallest date and the largest date from my dictionary and store them as variables. The integer item will not always necessarily be in ascending order, so I cannot use that.

I tried the following with no luck:

debug.print worksheetfunction.min(datedict.keys)

I don’t want to create a loop that checks each key and compares it to the previous one if I don’t have to. Is there a quicker and easier way to accomplish what I need?

How to&Answers:

When you put dates as keys, the dictionary converts them to strings, so any later comparison as numbers, such as Application.min(datedict.keys) will fail.

As solution, convert those dates to numbers prior to inserting in the dictionary. You can use CLng(myDate) because you care only about the day, not the time.

Sub Test()
  Dim d As Date, datedict As New Dictionary

  d = DateSerial(2017, 6, 26)
  datedict.Add CLng(d), 1      ' <--- convert to long prior to insertion

  d = d - 1
  datedict.Add CLng(d), 2

  d = d + 5
  datedict.Add CLng(d), 3

  Dim minD As Date, maxD As Date
  minD = Application.min(datedict.Keys)
  maxD = Application.Max(datedict.Keys)
  Debug.Print minD, maxD
End Sub

Output:

6/25/2017 6/30/2017