我正在运行一个宏,它要求一个工作表名称和一个参考单元格,然后选择一个单元格范围,围绕我们选择的单元格。在对我的数据应用筛选器之后,有些行变得隐藏起来,因为它们是不需要的。问题是,宏没有考虑到这一点,并计算隐藏行。以下是我在宏的原始版本中使用的代码:
…在应用一些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.Offset
与SpecialCells(xlCellTypeVisible)
相结合,导致上述宏的功能-即选择一系列单元格,避免过滤后的隐藏行?
要从选定的单元格范围中只选择可见的单元格,可以使用以下代码行:
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