xlCellTypeVisible不返回过滤范围,而是整个范围

use*_*660 5 excel vba excel-vba

好的,大家对此感到莫名其妙...

我在Access中的Excel中有一个链接表。我正在尝试编写一个vba函数,该函数返回该表给定列的过滤范围地址。请记住,我正在尝试使用结构化引用(例如Table1 [[#Data],[Column2]]),因为它是一个链接表,并且旨在随时间刷新和更改。

我使用xlCellTypeVisible无济于事。该函数仍然返回整个范围,即使它已被过滤。

更令人困惑的是,我创建了一个几乎相同的Sub(而不是Function,因此我可以逐步执行),该Sub 正确返回所需的收益!我难过了;我只是不能在函数中复制它。我怀疑这与结构化引用有关。

功能“filteredRange”错误地返回的整个范围“$ F $ 2:$ F74”,当我进入这个到Excel中的任意单元格。

=filteredRange(Table_RyanDB[[#Data],[LC]])
Run Code Online (Sandbox Code Playgroud)

而以下子“测试”确实返回正确答案“ $ F $ 2:$ F $ 14”。我似乎无法辨别为什么它们的输入变量输出不相同。

Sub test()
    Dim theRange As Range
    Set theRange = Range("Table_RyanDB[[#Data],[LC]]")
    MsgBox theRange.Rows.SpecialCells(xlCellTypeVisible).Address
End Sub



Function filteredRange(theRange As Range)
    filteredRange = theRange.SpecialCells(xlCellTypeVisible).Address
End Function
Run Code Online (Sandbox Code Playgroud)

Dmi*_*liv 5

Excel UDF 有一些限制SpecialCells(xlCellTypeVisible)在这里不能正常工作。改用这个:

Function filteredRange(theRange As Range)
    Dim rng As Range
    Dim r As Range

    For Each r In theRange.Rows
        If Not r.Hidden Then
            If rng Is Nothing Then
                Set rng = r
            Else
                Set rng = Union(rng, r)
            End If
        End If
    Next
    If Not rng Is Nothing Then filteredRange = rng.Address
End Function
Run Code Online (Sandbox Code Playgroud)

  • @ckuhn203 `.SpecialCells` 是一个范围对象的方法,虽然它没有说明*哪些*方法受到影响,但根据文档,“大多数”方法无法执行。 (3认同)