首页 > 解决方案 > 使用 vba 在 excel 范围内查找特定行

问题描述

我需要在工作表上找到满足给定条件的行。我多次看到作者通过根据搜索条件进行过滤来执行此操作,但我不喜欢这种方法,所以我使用了类似的方法。

Sub fi()
    Dim lastRow As Long
    lastRow = 100
    Dim myRow As Long
    For i = 1 To lastRow
        If Cells(i, 1) = "value1" And Cells(i, 3) = "value2" And Cells(i, 4) = "value3" Then
            i = myRow
        End If
    Next i
End Sub

你们有没有一些好的做法可以以更有效的方式做到这一点?这些是一种按行包含 10 个单元格的订单,但我可以根据其中三个找到我需要的东西。这是典型的 sql select 语句,但这里我不能使用 sql。谢谢

标签: excelvba

解决方案


试试这个(代码中的必要注释):

Sub fi()
    Dim lastRow As Long, foundRange As Range
    'this will find last row for you, don't need to hard-code it
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    'I used nested ifs, as it will boost the performance
    'it will stop checking next conditions if preceding condition fail
    For i = 1 To lastRow
        If Cells(i, 1) = "value1" Then
        If Cells(i, 3) = "value2" Then
        If Cells(i, 4) = "value3" Then
            'add columns A through J to foundRange
            If foundRange Is Nothing Then
                Set foundRange = Range(Cells(i, 1), Cells(i, 10))
            Else
                Set foundRange = Union(foundRange, Range(Cells(i, 1), Cells(i, 10)))
            End If
        End If
        End If
        End If
    Next i
    foundRange.Select
End Sub

推荐阅读