查找下一条记录命令按钮

时间:2018-10-18 19:26:14

标签: excel vba excel-vba

我需要你的帮助,

我似乎无法让下一个或上一个按钮与excel的.FindNext和FindPrevious函数一起使用。

我的目的是创建一个用户表单,用户可以使用下一个和上一个按钮在找到的“ test”匹配项之间返回第四个。我以为,通过全局化变量foundCell,我也许可以完成此操作,但是我确实错了。

Dim foundCell

Private Sub btnSearch_Click()

    With Sheet1
        Set foundCell = .Cells.find(What:="test", After:=.Cells(1, 1), _
        LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    End With

    If Not foundCell Is Nothing Then
            MsgBox ("""Bingo"" found in row " & foundCell.Row)
            form1.location.Value = Cells(foundCell.Row, 1).Value
    Else
            MsgBox ("Bingo not found")
    End If

End Sub

Private Sub btnNext_Click()
    foundCell.FindNext
    form1.location.Value = Cells(foundCell.Row, 1).Value
End Sub

Private Sub btnPrev_Click()
    foundCell.FindPrevious
    form1.location.Value = Cells(foundCell.Row, 1).Value
End Sub

1 个答案:

答案 0 :(得分:1)

我将采用您的搜索例程并将其移至子例程。然后,您可以通过传入一些参数来调用它。例如要搜索的起始单元格以及前进方向。

Private Sub btnSearch_Click()
dosearch Cells(1, 1), Excel.xlNext
End Sub

Private Sub btnNext_Click()
    dosearch foundCell, Excel.xlNext
End Sub

Private Sub btnPrev_Click()
    dosearch foundCell, Excel.xlPrevious
End Sub

Sub dosearch(r As Range, whichWay As Integer)
With Sheet1
        Set foundCell = .Cells.Find(What:="test", After:=r, _
        LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=whichWay, MatchCase:=False, SearchFormat:=False)
End With

    If Not foundCell Is Nothing Then
            MsgBox ("""Bingo"" found in row " & foundCell.Row)
            form1.Location.Value = Cells(foundCell.Row, 1).Value
    Else
            MsgBox ("Bingo not found")
    End If

End Function