2017-04-05 75 views
6

根据@Chips Ahoy构成的question,我决定创建一个UDF来查找某个范围内可见单元格的PercentRank。SpecialCells(xlCellTypeVisible)不能在UDF中工作

虽然@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,64位上使用Excel/Office 2013,64位。

脑油炸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 
+0

删除'Rows.':'x.SpecialCells(xlCellTypeVisible).Address' –

+0

试过@ScottCraner,没有变化很遗憾。 – CLR

回答

4

看来SpecialCells已知在UDF中失败。 几个来源:123

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

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 
+2

谢谢@CallumDA,这很完美。看起来像微软有一个错误修复,并没有胃口去做。 – CLR

相关问题