访问非连续可见细胞的索引

时间:2016-12-12 18:30:45

标签: excel vba excel-vba

我有一个数据表,根据用户的自动筛选选项过滤列“Product”。我还将“Product”定义为动态命名范围,我们将此定义为A2:A30。之后,我想进一步操纵可见细胞。我的调试代码片段:

df$mean <- apply(df[1:5], 1, mean)
df$wt.mean <- apply(df[1:5], 1, weighted.mean, weight)

xName.Count将始终返回正确数量的可见单元格,但在处理非连续的隐藏单元格时,访问xName索引会很麻烦。例如,如果A2:A5和A8:A11是隐藏单元格,xName(1)将返回A6的值,但xName(3)将返回A8的值而不是A12的值。这使我几乎不可能只穿过可见细胞。

我是否只能使用可见单元格进行索引操作?任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:1)

对于非连续范围,您可以使用For Each循环。

E.g。

Sub Tester()

    Dim rng As Range, rw As Range

    'create a non-contiguous test range
    Set rng = Range("A3:D4,A7:D7,A10:D16")

    'loop over each row in the range
    For Each rw In rng.Rows
        Debug.Print rw.Address()
    Next rw

End Sub

答案 1 :(得分:0)

也许这就是你想要做的事情:迭代范围区域,因为隐藏范围已经分割成许多区域。

Set xName =ThisWorkbook.Names("Product").RefersToRange.SpecialCells(xlCellTypeVisible)

For i = 1 to xName.Areas.Count
    For j = 1 to XName.Areas(i).Count
        Debug.Print i, j, XName.Areas(i).Cells(j)
     Next
Next

答案 2 :(得分:0)

我的建议:

Sub test()
    Dim xName As Range
    Set xName = ThisWorkbook.Names("Product").RefersToRange.SpecialCells(xlCellTypeVisible)
    Debug.Print xName.Count
    Debug.Print VisibleCell(xName, 3)
End Sub

Function VisibleCell(rng As Range, index As Long) As Range
    Dim i As Long
    Dim r As Long
    i = 0
    r = 1
    Do
        Do While rng(r).EntireRow.RowHeight = 0 Or rng(r).EntireColumn.ColumnWidth = 0
            r = r + 1
        Loop
        i = i + 1
        If i = index Then
            Set VisibleCell = rng(r)
            Exit Do
        End If
        r = r + 1
    Loop
End Function