提问人:Gerry Hartman 提问时间:11/14/2023 最后编辑:braXGerry Hartman 更新时间:11/14/2023 访问量:39
使用 时仅对可见单元格进行寻址。SpecialCells(xlCellTypeVisible) 方法
Addressing Only Visible Cells when Using the .SpecialCells(xlCellTypeVisible) Method
问:
我希望仅对筛选后的表格范围的可见单元格执行计算。我可以使用 .SpecialCells(xlCellTypeVisible) 方法,但是当我遍历生成的范围时,代码似乎正在寻址不可见的单元格。
数据:在此输入图片描述
过滤数据:在此处输入图像描述
法典:
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
相当难题。我非常感谢任何帮助 - 谢谢!
答:
0赞
taller
11/14/2023
#1
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赞
Gerry Hartman
11/14/2023
#2
嗯,这很有趣 - 我在提出问题后立即解决了它。我不应该使用索引遍历范围,我应该在过滤的范围内使用 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赞
Black cat
11/14/2023
#3
对此结果的解释是,如果一个区域包含不连续的单元格,则生成的 Range 对象具有“区域”,即连续范围的列表。
这可以通过范围的属性来实现。Areas
试试这个
set a=shTable.Range("A2:A7").SpecialCells(xlCellTypeVisible)
For i=1 To a.Areas.Count
Debug.Print a.Areas(i).Address
Next i
评论