【问题标题】:VBA Loop through Visible cells onlyVBA 仅循环通过可见单元格
【发布时间】:2016-06-10 21:36:16
【问题描述】:

我正在使用下面的代码循环遍历每一行,但是我只想循环遍历 B 列中的可见单元格(因为我已经过滤掉了我想忽略的值),范围从第 10 行 -194 行。有谁知道我会怎么做?

For X = 192 to 10 Step -1
    If Range("B" & X).Text = "" Then **This needs to change to visible cells only but not sure how!
        Code required insert here
    Else
    End If
Next X

【问题讨论】:

  • If Range("B" & X).entirerow.hidden=false?

标签: vba excel


【解决方案1】:
Dim cell as Range
With Range("B10:B192").SpecialCells(xlCellTypeVisible)
   For X = .Rows.Count to 1 Step -1
       Set cell = Range("A" & X) ' this sets the current cell in the loop
   Next X
End With

【讨论】:

  • ooo 先设置范围再循环。无需测试^^
【解决方案2】:

行高为 0 表示该行被隐藏。所以你可以检查一下

For X = 192 to 10 Step -1
    If Worksheets("Sheet1").Rows(X).RowHeight > 0 Then
        Code required insert here
    End If
Next X

当然,假设您正在处理“Sheet1”。

【讨论】:

  • 太棒了。很高兴我能帮上忙。
【解决方案3】:

您需要第二个循环来遍历 Range.AreasRange.SpecialCells(xlCellTypeVisible)。每个区域可以是一行或多行。

    Dim a As Long, r As Long
    With Range("B10:B192").SpecialCells(xlCellTypeVisible)
        For a = .Areas.Count To 1 Step -1
            With .Areas(a)
                For r = .Rows.Count To 1 Step -1
                    'Debug.Print .Cells(r, 1).Address(0, 0)
                    'Debug.Print .Cells(r, 1).Text
                    If .Cells(r, "B").Text = "" Then
                        'Code required insert here
                    End If
                Next r
            End With
        Next a
    End With

您似乎想向后循环,所以我继续朝那个方向前进。如果意图是删除行,有更简单的方法来做到这一点。

【讨论】:

    【解决方案4】:
    Dim hiddenColumn: hiddenColumn = "B"
    For i = 1 To 10
        If Range(hiddenColumn & i).EntireRow.Hidden = False Then
            'logic goes here....
        End If
    Next
    

    【讨论】:

    • 除非我相信他想在单元格/行被隐藏时执行代码。
    • If Not (Range(hiddenColumn & i).EntireRow.Hidden) Then , hehe or If Range(hiddenColumn & i).EntireRow.Hidden = False Then
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 2017-08-21
    相关资源
    最近更新 更多