Find "closest" previous record that "matches" the current record

Find "closest" previous record that "matches" the current record

Has anyone (Damien Cregan?) found the best way to find the "closest"/"nearest" previous record that matches the current record without getting the "x is an empty set and values cannot be retrieved" error?

For example:

  1. RecordSet = FormA [Criteria 1 == x && Criteria2 == y && Added_Time >= "some date"];

  2. for each record in RecordSet
  3. {
  4.    if record.Field == SomeCriteria
  5.    {
  6.       PreviousRecord = FormA [Field1 = record.Field1 && Added_Time < record.Added_Time && ??????];
  7.    }
  8. }

This works in some situations, but the "Added_Time" criteria often kills the script (I assume) because the time frames aren't matching up.

I've tried:
  1. PreviousRecord = FormA [...] sort by Added_Time desc range from 0 to 0;
but I get "'PreviousRecord' is an empty set and values cannot be retrieved" error.

It'd be nice if I could reference RecordSet instead of Form A, but that's not possible plus the previous record I'm looking for may fall outside of that criteria (it might be before Added_Time).

Thoughts anyone?