简体   繁体   中英

Excel VBA - Find several row numbers for given value in table column

I am really new in VBA, and I am trying to get back the row numbers where I have "FALSE" in two columns of my workbook.

The code below worked to an extent, as it only stop at the first "FALSE" value and doesn't report it further than that in the Message Box, when I know there are more than one "FASE" value in the rest of the columns. How can I have all the rows with a "FALSE" value reported in the Message Box?

Dim CurrentWB As Workbook
 Set CurrentWB = ActiveWorkbook
 With ActiveWorkbook.Sheets("Sheet1")
    Set FindRow = .Range("J:J, K:K").Find(What:="FALSE", LookIn:=xlValues)
    If Not FindRow Is Nothing Then
        MsgBox ("FALSE found in row:" & FindRow.Row)
    Else
       MsgBox ("No FALSE found")
    End If

While it would be easier for you/user to have a filter on an array with the rows with a "FALSE" in, here's what you were looking for:

Sub testFind()
    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    Dim rngF As Range
    Dim CurrentWB As Workbook
    Dim startFind As Long
    Dim startStr As String
    
    Set CurrentWB = ActiveWorkbook
    With ActiveWorkbook.Sheets("Sheet1")
        Set FindRow = .Range("J:J, K:K").Find(What:="FALSE", LookIn:=xlValues)
        If Not FindRow Is Nothing Then
            startFind = FindRow.Row 'to get out of the infinite loop
            startStr = "FALSE found in row:"
            Do Until FindRow Is Nothing
                If Not dict.Exists(FindRow.Row) Then 'in case there's multiple "FALSE" in the row
                    dict.Add FindRow.Row, FindRow.Row 'add row to dictionary in case it's the first "FALSE"
                    startStr = startStr & FindRow.Row & ", " 'add row to your message
                End If
                Set FindRow = .FindNext(FindRow) 'next find
                If FindRow.Row = startFind Then: Set FindRow = Nothing 'we're back to start so we can exit the loop
                startStr = Left(startStr, Len(startStr) - 2) 'get rid of the last ", "
            Loop
            MsgBox startStr
        End If
    End With
End Sub

This is untested but I did grab it from one of my own subs and modified it to your specifications. Hope this is more understandable for you now:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM