2017-04-05 79 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

相關問題