RDO does not have a FindFirst or Seek method, and as a programmer, you sometimes need to quickly move to a particular record. I had a user who wanted to be able to scroll through more than 3,000 records and also be able to search for a particular record. A linear search was too slow, so I decided to write a binary search routine. The routine is case-insensitive and finds the matching entry. It can be copied into the form module and used for searches on any sorted column for a given resultset. It takes three arguments: the rdoResultset being searched, the column name within the resultset to be searched, and the search string:
Private Sub BinarySearch(ByRef rs _ As rdoResultset, ByVal strColName As _ String, ByVal varSearch As Variant) Dim lngFirst&, lngLast&, varBookMark varBookMark = rs.Bookmark 'set a bookmark lngLast = rs.RowCount If lngLast = 0 Then Exit Sub lngFirst = 0 rs.AbsolutePosition = (lngLast - lngFirst) _ 2 'move to middle varSearch = Trim(UCase(varSearch)) Do While ((lngLast - lngFirst) 2) > 0 Select Case StrComp(UCase(Left(Trim _ (rs.rdoColumns(strColName)), _ Len(varSearch))), varSearch, vbTextCompare) Case 0 'found Exit Sub Case -1 'still ahead lngFirst = rs.AbsolutePosition rs.Move (lngLast - lngFirst) 2 Case 1 'left behind lngLast = rs.AbsolutePosition rs.Move (-1) * ((lngLast - lngFirst) 2) End Select Loop rs.MoveLast If (StrComp(UCase(Left (Trim(rs.rdoColumns(strColName)), _ Len(varSearch))), varSearch, _ vbTextCompare)) <> 0 Then ' record not found. Return to bookmark and ' display message. rs.Bookmark = varBookMark MsgBox "Entry not found for " _ & varSearch, vbOKOnly Or _ vbInformation, "Binary Seacrh" End IfEnd Sub
Because this search always misses the last item, the last record is checked specifically. Also, this routine finds the last matching record if the record is positioned before the middle of a resultset, or the first matching record if the record is positioned after the middle of a resultset. For example, say there are three Smith’s?A. Smith, B. Smith, and C. Smith?in a resultset and the user is searching by last name for Smith. Also assume there are 100 records in the resultset. If C. Smith is at absolute position of 25 (< 50 = 100/2), then this search routine finds C. Smith first. However, if A. Smith has an absolute position of 59 (>50 = 100/2), then this search routine finds A. Smith first. In case the Smiths happen to be somewhere in the middle, this search routine finds the first Smith encountered. This routine works best for searching on unique keys, such as Social Security numbers.