Excel 选择筛选单元格内的单元格

问题描述 投票:0回答:1

我想选择已过滤单元格内的单元格。

示例

这是我的代码

子GoToNextVisibleCellBelow()

Do
    ActiveCell.Offset(1, 0).Select
Loop While ActiveCell.EntireRow.Hidden = True

结束子

它在我选择的列中下降 1 列。我可以根据需要多次运行此代码。然而,如图所示,虽然我可以在过滤的单元格中左右移动,但无法向上选择。 我该怎么选择如图所示的区域?

excel vba filtered
1个回答
0
投票
Option Explicit

Sub DelTopNRows()
    Dim visRng As Range, selRng As Range, iR As Long
    Dim ColCnt As Long, rRow As Range, rArea As Range
    Const ROWS_CNT = 4  ' modify as needed
    With ActiveSheet.Range("A1").CurrentRegion
        ColCnt = .Columns.Count
        Set visRng = .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible)
        If Not visRng Is Nothing Then
            If visRng.Cells.Count / ColCnt > ROWS_CNT Then
                For Each rArea In visRng.Areas
                    For Each rRow In rArea.Rows
                        If selRng Is Nothing Then
                            Set selRng = rRow
                        Else
                            Set selRng = Application.Union(selRng, rRow)
                        End If
                        iR = iR + 1
                        If iR = ROWS_CNT Then Exit For
                    Next
                    If iR = ROWS_CNT Then Exit For
                Next
            Else
                Set selRng = visRng
            End If
            If Not selRng Is Nothing Then selRng.EntireRow.Delete
        End If
    End With
End Sub

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.