查找符合特定条件的范围内的所有值,然后返回每行VBA

时间:2018-10-31 09:05:18

标签: excel vba for-loop search

我正在寻找一些代码来搜索某个范围,并返回该范围内符合特定条件的每个单元格的行号,并列出这些行。

以前,我只需要第一个值,因此一直在使用代码:

Dim Criteria1 As Single
Dim Criteria2 As Single
Dim Required As Integer
Dim Range1 As Range
Dim GearNeg1 As Integer

SetColumn = 24
Set Range1 = Sheets("X").Range("A2:BT72").Columns(SetColumn).Cells
Criteria1 = Sheets("X").Range("P111").Value
Criteria2 = Sheets("X").Range("Q111").Value

For Each Cell In Range1

    If Cell.Value < Criteria1 And Cell.Value > Criteria2 Then

        Required = Cell.row

        Exit For

    End If
Next

我一直在添加一个for循环,以将符合条件的值的所有行值返回到列表。但是我很挣扎,似乎只能达到每次找到的第一个值。

2 个答案:

答案 0 :(得分:0)

这是一个最小的示例,返回范围A1:A30中包含X的行:

Public Sub TestMe()

    Dim rowValues As String
    Dim myCell As Range

    For Each myCell In Worksheets(1).Range("A1:A30")
        If myCell = "X" Then
            rowValues = Trim(rowValues & " " & myCell.Row)
        End If
    Next myCell

    Debug.Print rowValues

End Sub

在这里通过串联完成返回:rowValues = Trim(rowValues & " " & myCell.Row),需要Trim()才能减少第一个串联的第一个" "

答案 1 :(得分:0)

您可以将范围读取到数组中,循环数组,并将符合条件的行连接为字符串。我使用的事实是您从第2行开始,并且我使用的是基于1的数组来确定行,即我将i的值加1(即合格值所在的数组中的索引)。

您也可以使用

required = required & "," & i + ws.Range("A2:BT72").Row - LBound(arr)

VBA:

Option Explicit
Public Sub test()
    Dim criteria1 As Single, criteria2 As Single, required As String
    Dim arr(), ws As Worksheet, setColumn As Long, i As Long

    Set ws = ThisWorkbook.Worksheets("X")
    setColumn = 24
    arr = Application.Transpose(ws.Range("A2:BT72").Columns(setColumn).Value)

    criteria1 = ws.Range("P111").Value
    criteria2 = ws.Range("Q111").Value

    For i = LBound(arr) To UBound(arr)
        If arr(i) < criteria1 And arr(i) > criteria2 Then
            required = required & "," & i + 1
        End If
    Next

    required = Replace$(required, ",", vbNullString, 1, 1)

    Debug.Print required
End Sub