Question : DoCmd.FindNext doesn't go to next find

I'm using two buttons:
  Find Button using Docmd.FindRecord to find the specified string (works)

  FindNext Button using Docmd.FindNext to find the next matching string (doesn't work,  keeps the current highlighted string highlighted).

Code as follows:

Private Sub cmdFindAnywhere_Click()
  Dim strFind         As String
 
  strFind = InputBox("Please enter search string.  Note: Will search Component Number, Description, and Comment fields.")
  If strFind = "" Then
    Exit Sub
  End If
  Me.txtComponentNum.SetFocus
  DoCmd.FindRecord strFind, acAnywhere, , acSearchAll, , acAll
End Sub

Private Sub cmdFindNext_Click()
  DoCmd.FindNext
End Sub

Answer : DoCmd.FindNext doesn't go to next find

This behavior is caused because setting the focus starts searching again at the beginning of the field. If the found text is the entire field, it should work as expected. To adjust for this, you will need to keep track of the found position in the field. I made some modifications; try this:

Dim strFind As String
Dim blnFound As Boolean
Dim ctlFound As Control, intFoundStart As Integer, intFoundLength As Integer

Private Sub cmdFindAnywhere_Click()
 
  blnFound = False
  intFoundStart = -1
  intFoundLength = -1
 
  strFind = InputBox("Please enter search string.  Note: Will search Component Number, Description, and Comment fields.")
  If strFind = "" Then
    Exit Sub
  End If
 
  Me.txtComponentNum.SetFocus
  DoCmd.FindRecord strFind, acAnywhere, , acSearchAll, , acAll

    On Error Resume Next
   
    Set ctlFound = Screen.ActiveControl
    With ctlFound
        If .SelText = strFind Then
            blnFound = True
            intFoundStart = .SelStart
            intFoundLength = .SelLength
        End If
    End With
   
    On Error GoTo 0

End Sub

Private Sub cmdFindNext_Click()

If Not blnFound Then
    MsgBox "Please click Find."
Else

'On Error Resume Next

With ctlFound
    .SetFocus
    If intFoundStart >= 0 Then
        .SelStart = intFoundStart
        .SelLength = intFoundLength
    End If
End With

    blnFound = False

  DoCmd.FindNext

    Set ctlFound = Screen.ActiveControl
    With ctlFound
        If .SelText = strFind Then
            blnFound = True
            intFoundStart = .SelStart
            intFoundLength = .SelLength
        End If
    End With
   
On Error GoTo 0

End If
   
End Sub

Private Sub Form_Unload(Cancel As Integer)

Set ctlFound = Nothing

End Sub

--
Random Solutions  
 
programming4us programming4us