我想使用命令按钮在活动工作表中的textbox2中搜索/查找值

时间:2013-01-31 06:25:30

标签: excel-vba vba excel

我想使用命令按钮

在活动工作表中的textbox2中搜索/查找值

这是我的代码:

Dim ws As Worksheet
Set ws = Worksheets("FSS-TEM-00025")
Dim FindString As String
    Dim Rng As Range    
    FindString = Me.TextBox2.Value
    If Trim(FindString) <> "" Then
        With ws.Range("A1:Z1048576")
            'Set Rng = .Find(What:=FindString, _
                            After:=.Cells(.Cells.Count), _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlNext, _
                            MatchCase:=False)'
             Set Rng = ws.Cells.Find(What:=FindString, SearchOrder:=xlRows, _
    SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1

            If Not Rng Is Nothing Then
                Application.Goto Rng, True
            Else
                MsgBox "Nothing found"
            End If
        End With
    End If


     Unload Me

1 个答案:

答案 0 :(得分:1)

试试这个。这对我有用

Option Explicit

Private Sub CommandButton1_Click()
    Dim ws As Worksheet
    Dim FindString As String
    Dim Rng As Range

    Set ws = ThisWorkbook.Worksheets("FSS-TEM-00025")

    FindString = TextBox2.Value

    If Trim(FindString) <> "" Then
        Set Rng = ws.Cells.Find( _
                         What:=FindString, _
                         LookIn:=xlValues, _
                         LookAt:=xlPart, _
                         SearchOrder:=xlByRows, _
                         SearchDirection:=xlNext, _
                         MatchCase:=False, _
                         SearchFormat:=False)

        If Not Rng Is Nothing Then
            Application.Goto Rng, True
        Else
            MsgBox "Nothing found"
        End If
    End If
End Sub

如果您要查找完整匹配项,请将LookAt:=xlPart更改为LookAt:=xlWhole

有关.Find here的更多信息。