VBA Loop through Visible cells only

2019-09-02 12:44发布

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

4条回答
爷、活的狠高调
2楼-- · 2019-09-02 12:51
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
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-09-02 12:51
Dim hiddenColumn: hiddenColumn = "B"
For i = 1 To 10
    If Range(hiddenColumn & i).EntireRow.Hidden = False Then
        'logic goes here....
    End If
Next
查看更多
趁早两清
4楼-- · 2019-09-02 12:55

A row height of 0 means the row is hidden. 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.

查看更多
祖国的老花朵
5楼-- · 2019-09-02 13:11

You need a second loop to iterate through the Range.Areas of Range.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.

查看更多
登录 后发表回答