10

假设我有 10 行数据。我对数据应用了一些过滤器,第 7 行和第 9 行被过滤 可见

我想遍历数据(10 行)并在空白列(假设 C列)中输出字符串“可见”适用于可见行(即范围 C7 和范围 C9)。

4

3 回答 3

26

Choose some of the first 10 rows to hide, and then try running this

Option Explicit

Sub CheckIfVisible()

Dim i As Integer, x As Integer
x = 0
For i = 1 To 10
    With Excel.ThisWorkbook.ActiveSheet
        If .Rows(i).EntireRow.Hidden Then
        Else
            .Cells(15 + x, 1) = "Row " & i & "is visible"
            x = x + 1
        End If
    End With
Next i

End Sub

Is this the sort of loop you're looking for?
Maybe you can show us your Loop so we can see where your problem is?

于 2013-01-05T16:34:20.587 回答
0

由于我前一阵子来这里寻找这个,这里有一些可能对未来的谷歌人有用的东西。

如果您按单元格/行执行此操作,则可以直接访问单元格.EntireRow.Hidden bool。

在下面的示例中,它只是通过选择中的每个单元格的 ForEach 循环,并仅读取该单元格中的属性,基于 .Hidden 为真/假进行计数/着色。

可能的陷阱要提防..

如果您正在测试过滤范围,则需要在范围之外选择一行,因为如果隐藏行落在范围中的倒数第二/最后一行,则可能无法捕获隐藏行,选择第一个可见行选择后避免了这种情况。

对于大范围(10,000 + 行)来说,这将是极其低效的

CopyPasta 如果你想测试



Sub HowManyHiddenCells()

Dim MyCell, MyRange As Range
Dim CellCountAll, CellCountVisible, CellCountHidden As Integer

Set MyRange = Selection



For Each MyCell In MyRange

    ':: IGNORE EMPTY ::
    If Len(MyCell.text) > 0 Then

        If MyCell.EntireRow.Hidden Then
        MyCell.Interior.Color = RGB(255, 220, 200)
        ':: Count of hidden cells in range
        CellCountHidden = CellCountHidden + 1
        ':: Do Column C Text! ::
        MyCell.Offset(0, 2).FormulaR1C1 = "I was hidden! "
        End If
    
        If MyCell.EntireRow.Hidden = False Then
        MyCell.Interior.Color = RGB(200, 255, 180)
        ':: Count of visible cells in range
        CellCountVisible = CellCountVisible + 1
        End If
        ':: Count of all cells in range
        CellCountAll = CellCountAll + 1
    End If
Next MyCell


MsgBox "Cells total " & CellCountAll & vbNewLine & "Hidden :  " & CellCountHidden & vbNewLine & "Visible : " & CellCountVisible, vbOKOnly + vbInformation, "Count of hidden vs visible"

End Sub

运行中的脚本示例 - 在过滤范围内,以红色突出显示隐藏

于 2020-05-27T23:40:44.160 回答
-1

受@whytheq 的启发,我想出了这个,所以它循环遍历selection 中的所有可见行:

Sub Loop_through_selected_rows()
Dim rng As Range: Set rng = ActiveWindow.RangeSelection
Dim i As Integer
For i = 0 To rng.Rows.Count - 1
    If Cells(rng.Row + i, 1).EntireRow.Hidden Then
    Else
        Cells(rng.Row + i, 1).Range("A1:E1").Select 'Set Range within row to your needs
        ' Do something here
    End If
Next
End Sub
于 2020-05-14T19:43:59.437 回答