SpecialCells(xlCellTypeVisible)不能在UDF中工作

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

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

当我运行以下时,两个地址输出读取相同。 在我使用公式=VisiblePercentRank($A$2:$A$41,0.5) ,尽pipe行3到11被自动filter隐藏,但是两个地址输出到即时窗口读取$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,64bit上使用Excel / Office 2013,64位。

脑炎更新

我发现我的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 

已知SpecialCells在UDF中失败。 有几个来源: 1,2,3

你必须创build自己的function。 也许是这样的:

 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