【问题标题】:Select a range, avoiding hidden cells, using ActiveCell.Offset()选择一个范围,避免隐藏单元格,使用 ActiveCell.Offset()
【发布时间】:2015-10-09 17:25:12
【问题描述】:

我正在运行一个宏,它要求输入工作表名称和参考单元格,然后选择一系列单元格,包围我们选择的单元格。 对我的数据应用过滤器后,某些行会被隐藏,因为它们不需要。 问题是,宏没有考虑到这一点,也计算了隐藏的行。 这是我在宏的原始版本中使用的代码:

.....应用一些 InputBox 并搜索用户的值后,执行以下行:

Range(ActiveCell.Offset(90, 0), ActiveCell.Offset(-252, 2)).Select
Selection.Copy

以这种方式隐藏的行包含在选择中。 我尝试了以下修改

Range(ActiveCell.Offset(90, 0), ActiveCell.Offset(-252, 2)).SpecialCells(xlCellTypeVisible).Select
Selection.Copy

但是没有成功。

我想知道,任何人都可以提出一种将ActiveCell.OffsetSpecialCells(xlCellTypeVisible) 结合使用的方法,从而产生上述宏的功能——即选择一系列单元格,避免过滤后隐藏的行?

【问题讨论】:

    标签: vba excel filter


    【解决方案1】:

    要从一系列选定单元格中仅选择可见单元格,您可以使用以下代码行:

    Selection.SpecialCells(xlCellTypeVisible).Select
    

    就像这个例子:

    Range(ActiveCell.Offset(90, 0), ActiveCell.Offset(-252, 2)).Select
    Selection.SpecialCells(xlCellTypeVisible).Select
        Selection.Copy
    

    下面的代码是关于如何计算行数的示例。 所以,但有一个问题你必须考虑。

    如果您将所选内容粘贴到原始工作表中,则在您复制所选内容的区域中可能存在隐藏行。 如果是这样,您复制的文本也将被隐藏。

    因此,您必须将数据复制到新工作表以避免该问题,或者您必须将数据复制到工作表 1 的底部。

    Option Explicit
    'Define a Constant for the Amount of Rows you Need
    Private Const ConstAmountRows As Integer = 40
    Sub Test()
        Dim intCountedRows As Integer
        Dim idx As Integer
        Dim intDifference As Integer
    
        idx = 0
        Do
            If Not (intCountedRows = ConstAmountRows) Then
                intCountedRows = ConstAmountRows
                idx = idx + 1
            End If
            Sheets("Sheet1").Select
            'Select the Range with the Amount of Rows you need ideally
            Range("A1:A" & intCountedRows + idx).Select
    
            'Select only the Visible Cells
            Selection.SpecialCells(xlCellTypeVisible).Select
            Selection.Copy
    
            Sheets("Sheet2").Select 'Select another Sheet
            '***-> Her you can select the Place you want to Paste the Text<-***
            Range("B1").Select
            ActiveSheet.Paste
    
            '*** Count the Rows that you Paste
            intCountedRows = Selection.Rows.Count
        'if the Counted Rows are not equal to the Amount. Repeat
        Loop While Not (intCountedRows >= ConstAmountRows)
    End Sub
    

    【讨论】:

    • 感谢您对 Moosli 的建议。我只是使用了您建议的语法。但是在运行更新后的宏后,我可以看到电子表格中选择的区域是 A2336:C2678,而在 row2336 和 row2678 之间有隐藏的行。因此,当我粘贴选择时,我只得到 331 行(小于我的目标 343 行:))。有没有人建议如何使宏“补偿”隐藏行并根据隐藏行是在参考单元格的上方还是下方选择一些高于 2336 行或低于 2678 的行?
    猜你喜欢
    • 2016-12-14
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多