简体   繁体   English

VBA仅通过可见单元格循环

[英]VBA Loop through Visible cells only

I am using the below code to loop through each row however I only want to loop through visible cells in Column B (as I have filtered out the values I want to ignore) ranging from Row 10 -194. 我正在使用下面的代码遍历每一行,但是我只想遍历行10 -194内的B列中的可见单元格(因为我已经滤除了要忽略的值)。 Does anyone know how I would do this? 有人知道我会怎么做吗?

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
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

A row height of 0 means the row is hidden. 行高0表示该行是隐藏的。 So you could check for that 所以你可以检查一下

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

Assuming you are dealing with "Sheet1" of course. 假设您正在处理“ Sheet1”。

You need a second loop to iterate through the Range.Areas of Range.SpecialCells( xlCellTypeVisible ). 您需要第二个循环遍历迭代Range.AreasRange.SpecialCells( xlCellTypeVisible )。 Each Area could be one or more rows. 每个区域可以是一排或多排。

    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

It seems you want to loop backwards so I continued with that direction. 看来您想向后循环,所以我继续朝这个方向前进。 If the intention was to delete rows, there are easier ways to do that. 如果要删除行,则有更简单的方法可以删除行。

Dim hiddenColumn: hiddenColumn = "B"
For i = 1 To 10
    If Range(hiddenColumn & i).EntireRow.Hidden = False Then
        'logic goes here....
    End If
Next

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM