搜索多个值并选择

时间:2016-03-01 01:04:48

标签: excel vba excel-vba

到目前为止,我有一个excel文件

http://i.stack.imgur.com/zX3xC.png

我的问题是,我希望能够在按下搜索按钮后输入一个数字,并显示一个输入框,搜索栏中的数字用于选择电子表格中匹配的所有数字。

另外还可以添加几个数字(40,21,33用逗号分隔)

我目前的代码是:

Sub SEARCH_Click()
    Dim sh1 As Sheet1
    Dim rng As Range
    Dim uname As String

    Set sh1 = Sheet1: uname = InputBox("Input")
    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
    End With

    With sh1
        .AutoFilterMode = False
        Set rng = .Range("A4", .Range("A" & .Rows.Count).End(xlUp))
        On Error Resume Next
        rng.SpecialCells(xlCellTypeVisible).Select
        If Err.number <> 0 Then MsgBox "Data not found" _
            Else MsgBox "All matching data has been selected"
        .AutoFilterMode = False
        On Error GoTo 0
    End With

    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
    End With
End Sub

我对编码很新,所以很多都来自互联网研究等。

1 个答案:

答案 0 :(得分:1)

放弃AutoFilter method赞成Range.Find method。虽然最终可以将一系列.AutoFilters应用于每一列,但只需使用Union method从.Find操作中收集结果就更有意义了。

Private Sub CommandButton1_Click()
    Dim uname As String, sh1 As Worksheet   '<~~ there is no var type called Sheet1
    Dim v As Long, fnd As Range, rng As Range, addr As String, vals As Variant

    Set sh1 = Sheet4

    uname = InputBox("Search for...")
    vals = Split(Replace(uname, Chr(32), vbNullString) & Chr(44), Chr(44))
    ReDim Preserve vals(UBound(vals) - 1)

    With sh1
        For v = LBound(vals) To UBound(vals)
            If IsNumeric(vals(v)) Then vals(v) = Val(vals(v))
            Set fnd = .Cells.Find(What:=vals(v), LookIn:=xlValues, LookAt:=xlWhole, _
                                  SearchOrder:=xlByRows, SearchFormat:=False)
            If Not fnd Is Nothing Then
                addr = fnd.Address
                Do
                    If rng Is Nothing Then
                        Set rng = fnd
                    Else
                        Set rng = Union(rng, fnd)
                    End If
                    Set fnd = .Cells.FindNext(after:=fnd)
                Loop Until addr = fnd.Address
            End If
            addr = vbNullString
            Set fnd = Nothing
        Next v
        If Not rng Is Nothing Then rng.Select
    End With

End Sub

在应用Range .Select¹方法后,您不想清楚要执行哪些操作。我建议一个简单的With ... End With statement woudl允许你继续处理 rng 不连续的Range object而根本不选择它。

search_and_select

¹有关远离依赖选择和激活以实现目标的更多方法,请参阅How to avoid using Select in Excel VBA macros