VBA:在 For/Each 循环中引用活动单元格的行

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

我的问题的目的是找到一个特定的值(文本),然后在 For/Each 循环中引用整行(或者更好的是只引用我的活动单元格右侧的使用范围) .

第一部分可以很好地找到我的值,但是,用于定位活动单元格行(因此查找函数找到的单元格)的代码还不起作用:

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

以下代码将找到您找到的单元格右侧的范围,并使用您的循环对该范围内的每个单元格进行比较。该部分可能可以通过使用 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