【问题标题】:VBA: Referring to active cells' row in a For/Each loopVBA:在 For/Each 循环中引用活动单元格的行
【发布时间】:2022-01-07 12:24:25
【问题描述】:

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

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

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

【问题讨论】:

  • 为什么你认为ActiveCell对应找到的cell?它不是。 ActiveCell 不会被 Cell.Find 更改。
  • @Storax 哦,谢谢,很高兴知道!在这种情况下,我将如何引用找到的单元格行?
  • 使用For Each cell 将使Set cell = Cells.Find(... 无用。您应该使用不同的变量而不是 cellcel,例如。因此,您应该声明 Dim cell As Range, cel as Range 并使用 cel 进行迭代。然后,在您尝试迭代的行中是否有字符串看起来像数字?否则,您应该使用If cell.Value = 0 Then。没有双引号。并且不要迭代整行。如果范围内没有空格,可以使用If cel.Value = "" Then Exit For,或者判断哪一列是最后一列。
  • @FaneDuru 谢谢!实际上,我之前有两个变量作为 Range,但不知道如何引用“单元格”的位置以遍历它的行。目前,迭代更多的是用于进一步代码的占位符,但感谢您的提示,您是对的!

标签: vba loops foreach


【解决方案1】:

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

【讨论】:

  • 非常感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-27
  • 2015-11-12
  • 1970-01-01
  • 2021-10-01
相关资源
最近更新 更多