• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1099
  • Last Modified:

Find closest date in sorted vba collection

Hello,

I have a sorted Collection containing dates (Excel VBA).  I need to find the closest date in the collection to a date 12 months prior to the current date.  Although the data is in a collection it can be put into another object such as an Array if that makes more sense to do this.

I'd appreciate any thoughts on the best way to do this.

Thanks.
0
tim_chamberlain
Asked:
tim_chamberlain
  • 2
1 Solution
 
Wayne Taylor (webtubbs)Commented:
Try the below function. To find the closest date to a date 12 months prior to today, you would use it like this....

    Dim dt As Date
    dt = FindClosestDate(DateAdd("m", -12, Date), coll)

Wayne
Function FindClosestDate(dt, coll As Collection) As Date
    Dim diff As Long: diff = 99999
    Dim closest As Date, d As Long
    For d = 1 To coll.Count
        If Abs(DateDiff("d", coll(d), dt)) < diff Then
            closest = coll(d)
            diff = Abs(DateDiff("d", coll(d), dt))
        End If
    Next
    FindClosestDate = closest
End Function

Open in new window

0
 
tim_chamberlainAuthor Commented:
Perfect. Thanks very much Wayne.
0
 
calacucciaCommented:
Hi

90        Do While ie.busy Or Not ie.ReadyState = IE_READYSTATE.Complete: DoEvents: Loop

        htmlStr = ie.document.body.innerHTML
     
        pointer = InStr(1, htmlStr, "Future Events")
        pointer = InStr(pointer, htmlStr, "vAlign")
        htmlStr = Mid(htmlStr, pointer + 18, 9)
        Range("B5").Value = htmlStr

100       Set doc = ie.document

The additional lines between 90 & 100 passed the test on your first sample (A5), did not test it further, but I think it should work for all.
0
 
calacucciaCommented:
Apologies, wrong question, disregard my comment.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now