使用 .SpecialCells(xlCellTypeVisible) 方法时仅寻址可见单元格

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

我希望仅对筛选表格范围的可见单元格执行计算。我可以使用 .SpecialCells(xlCellTypeVisible) 方法设置过滤范围,但是当我循环遍历结果范围时,代码似乎正在处理不可见的单元格。

数据: enter image description here

过滤数据: enter image description here

代码:

    Dim Filter_Range As String
    Dim h As Integer
    Set FilteredRecord = shTable.Range("A2:A7").SpecialCells(xlCellTypeVisible)
    Debug.Print "Filtered count: " & FilteredRecord.Count
    Debug.Print "Filtered address: " & FilteredRecord.Address
    For h = 1 To FilteredRecord.Count
        Debug.Print h & " = " & FilteredRecord(h) & "/address: " & FilteredRecord(h).Address
    Next

输出:

    A2:A7
    Filtered count: 4
    Filtered address: $A$2,$A$4,$A$6:$A$7
    1 = ABC/address: $A$2
    2 = DEF/address: $A$3
    3 = ABC/address: $A$4
    4 = DEF/address: $A$5

因此计数和过滤后的地址范围是完全正确的,但单步执行过滤后的范围返回的值只是前 4 行数据,包括应该隐藏的值($A$3 和 $A$5)。以下是我预期的结果:

    1 = ABC/address: $A$2
    2 = ABC/address: $A$4
    3 = XYZ/address: $A$6
    4 = XYZ/address: $A$7

真是个难题。我非常感谢任何帮助 - 谢谢!

excel vba cell visible
3个回答
0
投票

FilteredRecord(h)
相当于
FilteredRecord.Item(h)
。其结果与
FilteredRecord.Cells(h)
相同。对于非连续范围,它不是目标范围内的迭代。

请尝试一下。

Sub demo()
    Dim Filter_Range As String
    Dim c As Range, h As Long
    Set FilteredRecord = ActiveSheet.Range("A2:A7").SpecialCells(xlCellTypeVisible)
    Debug.Print "Filtered count: " & FilteredRecord.Count
    Debug.Print "Filtered address: " & FilteredRecord.Address
    h = 1
    For Each c In FilteredRecord.Cells
        Debug.Print h & " = " & c.Value & "/address: " & c.Address
        h = h + 1
    Next
End Sub

0
投票

这很有趣 - 我在提出问题后立即解决了它。我不应该使用索引迭代范围,我应该在过滤范围上使用 For Each。以下修改后的代码可以完美运行:

    Dim FilteredRecord As Range
    Dim Record As Range
    Dim h As Integer
    Filter_Range = "A2:A7"
    Set FilteredRecord = shTable.Range("A2:A7").SpecialCells(xlCellTypeVisible)
    Debug.Print "Filtered count:" & FilteredRecord.Count
    Debug.Print FilteredRecord.Address
    For Each Record In FilteredRecord.Rows
           Debug.Print Record & "/address: " & Record.Address
    Next

输出是:

Filtered count:4
Filtered address: $A$2,$A$4,$A$6:$A$7
ABC/address: $A$2
ABC/address: $A$4
XYZ/address: $A$6
XYZ/address: $A$7

0
投票

此结果的解释是,如果范围包含非连续单元格,则结果 Range 对象具有“区域”,即连续范围的列表。这可以通过范围的

Area
属性来实现。

试试这个

set a=shTable.Range("A2:A7").SpecialCells(xlCellTypeVisible)
For i=1 To a.Areas.Count
  Debug.Print a.Areas(i).Address
Next i
© www.soinside.com 2019 - 2024. All rights reserved.