Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

VBA: Referring to active cells' row in a For/Each loop

the aim of my problem is to find a specific value (Text) and then refer to the entire row (or even better only the used range to the right of my active cell) in a For/Each loop.

The first part works fine of finding my value, however, the code for targeting the row of the active cell (so the cell found by the find function), does not work yet:

Sub Search()
Dim cell As Range
Dim Count As Long
Set cell = Cells.Find(what:="Planned Supply at BP|SL (EA)", LookIn:=xlValues, lookat:=xlWhole)
For Each cell In ActiveCell.EntireRow
 If cell.Value = "0" Then
    Count = Count + 1
 End If
Next cell

Range("I1").Value = Count

End Sub

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The following code will find the range to the right of your found cell and use your loop to do the comparision for each cell in the range. That part could probably be improved by using WorksheetFunction.CountIf.

Option Explicit

Sub Search()
    
    Dim wks As Worksheet
    Set wks = ActiveSheet
    
    Dim cell As Range, sngCell As Range
    Dim Count As Long
    Set cell = wks.Cells.Find(what:="Planned Supply at BP|SL (EA)", LookIn:=xlValues, lookat:=xlWhole)
    
    If cell Is Nothing Then Exit Sub  ' just stop in case no hit
    
    Dim rg As Range, lastColumn As Long
    With wks
        lastColumn = .Cells(cell.Row, .Columns.Count).End(xlToLeft).Column  ' last used column in cell.row
        Set rg = Range(cell, .Cells(cell.Row, lastColumn))                  ' used rg right from found cell inlcuding found cell
    End With
    
   ' loop from the original post
    For Each sngCell In rg
        If sngCell.Value = "0" Then
            Count = Count + 1
        End If
    Next

    Range("I1").Value = Count

End Sub
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading