SpecialCells(xlCellTypeVisible)在UDF中不起作用

时间:2017-04-05 14:38:19

标签: excel vba excel-vba

基于@Chips Ahoy提出的question,我决定创建一个UDF来查找范围内可见单元格的PercentRank。

虽然@Chips似乎对我的语法更正感到满意,但实际上我无法让我的UDF正常工作。

当我运行以下时,两个地址输出读取相同。在我使用公式=VisiblePercentRank($A$2:$A$41,0.5)的示例中,尽管第3行到第11行被自动过滤器隐藏,但两个地址都输出到即时窗口$A$2:$A$41

代码:

Function VisiblePercentRank(x As Range, RankVal As Double)
    Debug.Print x.Address, x.Rows.SpecialCells(xlCellTypeVisible).Address
    VisiblePercentRank = WorksheetFunction.PercentRank(x.Rows.SpecialCells(xlCellTypeVisible), RankVal)
End Function

同时尝试删除.Rows

Function VisiblePercentRank(x As Range, RankVal As Double)
    Debug.Print x.Address, x.SpecialCells(xlCellTypeVisible).Address
    VisiblePercentRank = WorksheetFunction.PercentRank(x.SpecialCells(xlCellTypeVisible), RankVal)
End Function

如果第二个输出未读取$A$2,$A$12:$A$41或我错过了什么?

在Win7上使用Excel / Office 2013,64位,64位。

BRAIN FRYING UPDATE

如果我从即时窗口运行它,我发现我的UDF有效:

?VisiblePercentRank(range("A2:A41"),0.5)
$A$2:$A$41    $A$2:$A$11,$A$39:$A$41
 0.207 

但是如果从单元格公式=VisiblePercentRank(A2:A41,0.5)

运行
$A$2:$A$41    $A$2:$A$41

1 个答案:

答案 0 :(得分:4)

似乎已知Function VisiblePercentRank(x As Range, RankVal As Double) Debug.Print x.Address, VisibleCells(x).Address VisiblePercentRank = WorksheetFunction.PercentRank(VisibleCells(x), RankVal) End Function Private Function VisibleCells(rng As Range) As Range Dim r As Range For Each r In rng If r.EntireRow.Hidden = False Then If VisibleCells Is Nothing Then Set VisibleCells = r Else Set VisibleCells = Union(VisibleCells, r) End If End If Next r End Function 在UDF中失败。 一些来源:123

您必须创建自己的功能。也许是这样的:

{{1}}