VBA Search Code Error

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • captainmorgan
    New Member
    • Mar 2007
    • 10

    #1

    VBA Search Code Error

    I have included an unbound field called [search] which is used to quickly move to the desired record, by searching the last name field.

    I have been using this code for a few years, with only one hitch...if the entry is greater than the last record (sorted alpha), i get the following error;

    3021 modexpres.binar ysearch DAO.Field No current record

    (eg. if the last sorted record is Zimmerman, and I search Zo - i get this error)

    it does not occur for BOF (eg. if first sorted record is Butler, and I search A - it directs me to Butler)

    I have included my VBA searching code, please suggest a fix;

    VBA CODE BEGINS HERE ---------------------------------------

    Private Sub search_Change()

    Dim rst As Recordset
    Dim findtxt As String
    Call binarysearch(se arch.Text)

    If search.SelLengt h > 0 Then
    search.SelStart = search.SelLengt h
    End If
    End Sub


    Public Function binarysearch(se archadv As String, Optional searchrec As String)
    Dim movespot As Long
    Dim rst As Recordset

    On Error GoTo err

    Set rst = Me.RecordsetClo ne
    searchadv = searchadv
    rst.MoveFirst
    movespot = rst.RecordCount

    Do
    movespot = movespot / 2
    rst.Move (movespot)
    If StrComp(rst("la stname"), searchadv) < 1 Then
    Else
    rst.Move (0 - movespot)
    If rst.EOF Or rst.BOF Then
    rst.MoveFirst
    End If
    End If
    Loop Until movespot < 2


    If searchrec = "" Then
    Do Until StrComp(rst("la stname"), searchadv) > -1
    rst.MoveNext
    Loop

    Else
    If Not rst.EOF Then
    Do Until rst("prime_no") = searchrec
    rst.MoveNext
    If rst.EOF Then
    Exit Do
    End If
    Loop
    End If
    End If
    If rst.EOF And searchrec <> "" Then
    rst.MoveFirst
    rst.FindFirst "prime_no =" & searchrec
    End If
    Me.Bookmark = rst.Bookmark
    rst.close
    Exit Function

    err:
    MsgBox err.Number & " " & "modexpres.bina rysearch " & err.Source & " " & err.Description , vbCritical
    End Function

    Private Sub search_Click()

    search = ""

    End Sub
  • pks00
    Recognized Expert Contributor
    • Oct 2006
    • 280

    #2
    everytime u do a recordset move, u should check for no record i..e no current record by checking EOF/BOF. I see u are doing in most places but I reckon u need one here - your existing code, u do a move and assume it has worked. Even if u expect it to work, u must always check EOF/BOF flags before using rst("lastname")

    rst.Move (movespot)
    If StrComp(rst("la stname"), searchadv) < 1 Then
    Else


    again, here

    If searchrec = "" Then
    Do Until StrComp(rst("la stname"), searchadv) > -1
    rst.MoveNext
    Loop


    basically somewhere in your code u have reached EOF or BOF but continue to check a field.

    Comment

    Working...