使用excel vba搜索多个值

时间:2016-12-31 01:56:59

标签: excel vba excel-vba

下面的代码有助于搜索在单元格K8中输入的值并返回与其相关的值。我需要帮助搜索多个值,需要搜索范围K8:K30中输入的所有值,并且需要显示与它们相关的记录。

Sub finddata()
    Dim emstring As String

    Dim finalrow As Integer
    Dim i As Integer

    Sheets("Sheet1").Range("P3:X37").ClearContents

    emstring = Sheets("sheet1").Range("K8").Value
    finalrow = Sheets("Sheet1").Range("A6000").End(xlUp).Row

    For i = 2 To finalrow
        If Cells(i, 2) = emstring Then
          Range(Cells(i, 1), Cells(i, 3)).Copy
          Range("P6000").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
        End If
    Next i
End Sub

2 个答案:

答案 0 :(得分:0)

在这里,一个带有额外长度检查的嵌套For循环:

Sub finddata()
    Dim emstring As String

    Dim finalrow As Integer
    Dim i As Integer

    Sheets("Sheet1").Range("P3:X37").ClearContents

    emstring = Sheets("sheet1").Range("K8").Value
    finalrow = Sheets("Sheet1").Range("A6000").End(xlUp).Row

    Dim ctrSearchRow As Integer

        For i = 2 To finalrow
            For ctrSearchRow = 8 To 30
                emstring = Sheets("Sheet1").Cells(ctrSearchRow, 11).Value
                If Len(emstring) > 0 Then
                    If StrComp(Cells(i, 2).Value, emstring, vbTextCompare) = 0 Then
                        Range(Cells(i, 1), Cells(i, 3)).Copy
                        Range("P6000").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
                    End If
                End If
            Next ctrSearchRow
        Next i
End Sub

答案 1 :(得分:0)

AutoFilter()使用设置为Operator的{​​{1}}参数可以在这里提供帮助:

xlFilterValues