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

aij0ehis  于 2023-11-20  发布在  其他
关注(0)|答案(3)|浏览(291)

我希望只对过滤后的表格区域的可见单元格执行计算。我可以使用.SpecialCells(xlCellTypeVisible)方法设置过滤后的区域,但当我循环遍历结果区域时,代码似乎在处理不可见的单元格。
数据:enter image description here
过滤数据:enter image description here
代码:

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

字符串
输出量:

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


因此,计数和筛选的地址范围是完全正确的,但是从筛选范围中返回的值只是前4行数据,包括应该隐藏的值($A$3和$A$5)。以下是我期望的结果:
真是个难题,我非常感谢任何帮助-谢谢!

zsohkypk

zsohkypk1#

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

  1. Sub demo()
  2. Dim Filter_Range As String
  3. Dim c As Range, h As Long
  4. Set FilteredRecord = ActiveSheet.Range("A2:A7").SpecialCells(xlCellTypeVisible)
  5. Debug.Print "Filtered count: " & FilteredRecord.Count
  6. Debug.Print "Filtered address: " & FilteredRecord.Address
  7. h = 1
  8. For Each c In FilteredRecord.Cells
  9. Debug.Print h & " = " & c.Value & "/address: " & c.Address
  10. h = h + 1
  11. Next
  12. End Sub

字符串

展开查看全部
hmtdttj4

hmtdttj42#

好吧,这很有趣-我在提出我的问题后就解决了它。我不应该用索引遍历范围,我应该在过滤范围上使用For Each。以下修改后的代码工作得很好:

  1. Dim FilteredRecord As Range
  2. Dim Record As Range
  3. Dim h As Integer
  4. Filter_Range = "A2:A7"
  5. Set FilteredRecord = shTable.Range("A2:A7").SpecialCells(xlCellTypeVisible)
  6. Debug.Print "Filtered count:" & FilteredRecord.Count
  7. Debug.Print FilteredRecord.Address
  8. For Each Record In FilteredRecord.Rows
  9. Debug.Print Record & "/address: " & Record.Address
  10. Next

字符串
输出为:

  1. Filtered count:4
  2. Filtered address: $A$2,$A$4,$A$6:$A$7
  3. ABC/address: $A$2
  4. ABC/address: $A$4
  5. XYZ/address: $A$6
  6. XYZ/address: $A$7

展开查看全部
ht4b089n

ht4b089n3#

这个结果的解释是,如果一个区域包含不连续的单元格,则结果Range对象具有“区域”,即连续区域的列表。
这可以通过范围的Areas属性来实现。
试试这个

  1. set a=shTable.Range("A2:A7").SpecialCells(xlCellTypeVisible)
  2. For i=1 To a.Areas.Count
  3. Debug.Print a.Areas(i).Address
  4. Next i

字符串

相关问题