【问题标题】:Identify row number where preceding cell value in column differ only in visible range识别列中前一个单元格值仅在可见范围内不同的行号
【发布时间】:2020-02-21 21:13:08
【问题描述】:

我希望检索可见范围内的行号(数据被过滤),其中当前检查的单元格不等于同一列中的前一个单元格。

我编写了以下代码,它确实返回了前面和当前(上/下)单元格之间更改的正确行,但是,在即时窗口中,它返回相同的行值 22 次,与我相同的次数有可见的行。我只需要返回一次行号。它必须发生在我拥有的 for i 循环中。非常感谢您的帮助。

Sub PreceedingVisibleCellDiff()
'find row number when cell value differs from cell above

Dim LastRow As Long, cl As Range, rng As Range

LastRow = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
Debug.Print "LastRow: " & LastRow

Set rng = Range("B5:B" & LastRow)

For Each cl In rng.SpecialCells(xlCellTypeVisible)

    For i = LastRow To 5 Step -1

    If Cells(i, 12) <> "" Then
        If Cells(i, 8) <> Cells(i, 8).Offset(-1) Then Debug.Print i
    End If

    Next i

Next cl

End Sub

【问题讨论】:

  • 循环遍历您的cl 范围,而不是i。你得到重复输出的原因是你的For Each 循环并没有真正做任何事情。它只是一遍又一遍地重复For i 循环。 (它将重复等于您的 rng 中可见单元格的数量
  • 就是这样!感谢您指出我早就应该看到的明显内容。
  • 作为建议,请保留最初的问题,然后将工作代码作为答案发布(您甚至可以将其标记为这样)。这样其他人就会了解问题所在以及如何解决。
  • @XLmatters - 如果您确实按照 Ricardo 的建议进行更新,社区将会受益。这样,以后遇到此问题的任何人都可以看到问题和解决方案
  • 我回滚了您的编辑。请在下面发布工作代码作为解决方案

标签: excel vba


【解决方案1】:

根据 urdearboy 上述建议的工作解决方案:

Sub PreceedingVisibleCellDiff()
'find row number when cell value differs from cell above

Dim LastRow As Long, cl As Range, rng As Range

LastRow = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
Debug.Print "LastRow: " & LastRow

Set rng = Range("B5:B" & LastRow)

For Each cl In rng.SpecialCells(xlCellTypeVisible)

    'check that colum L(12) has an action item
    If Cells(cl.Row, 12) <> "" Then
        'at the row in column H (8) where the preceding cell does not match, there is a
        'new action to be acted upon
        If Cells(cl.Row, 8) <> Cells(cl.Row, 8).Offset(-1) Then Debug.Print cl.Row

        '< do something here using cl.Row >

    End If

Next cl

End Sub

【讨论】:

    猜你喜欢
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    相关资源
    最近更新 更多