2015-02-11 146 views
0

當我輸入下面的函數在細胞中的一個UDF:使用VBA計數可見空白單元格?

Function VisibleBlankCells(r As Range) As Long 
    On Error Resume Next 
    VisibleBlankCells = Intersect(r.SpecialCells(xlCellTypeVisible), r.SpecialCells(xlCellTypeBlanks)).Count 
    On Error GoTo 0 
End Function 

r.SpecialCells(xlCellTypeBlanks)評估所有細胞r爲空,不管它們是否含有文本或沒有。這可能是什麼原因和替代解決方案?

+0

你有沒有嘗試刪除你的'在錯誤恢復下一個(不寒而慄)聲明,看看有沒有實際的錯誤? – 2015-02-11 08:59:54

回答

1

擺脫On Error Resume Next的一開始 - 你應該總是假設你的代碼會失敗並相應地解釋它,簡單地忽略錯誤只會使問題複雜化。

其次,不需要使用Intersect - 只需直接識別可見細胞,然後再使用另一個SpecialCells()方法來識別空白子細胞。

Function VisibleBlankCells(r As Range) As Long 
    VisibleBlankCells = r.SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeBlanks).Count 
End Function 

這個測試:

Sub test_code() 
    Dim r As Range: Set r = Selection 
    Debug.Print CountBlanks(r) 
End Sub 

Function CountBlanks(r As Range) As Long 
    CountBlanks = r.SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeBlanks).Count 
End Function 
+0

您使用的是什麼版本的Excel? – 2015-02-11 09:09:57

+0

2010 ...更多關於bla – EngJon 2015-02-11 09:11:25

+0

OP正在使用Excel 2013. xlCellTypeBlanks返回「正確」地址並在我在Selection上執行時計數。但不正確的時候,我用它作爲UDF,並在r上執行它作爲範圍 – user1283776 2015-02-11 09:12:10

0

這種篩選機制將無法在UDF工作(見this對這些信息)。我建議你的UDF內循環:

Public Function VisibleBlankCells(rng As Range) As Long 
    Dim i As Integer 
    Dim cell As Range 
    i = 0 
    For Each cell In rng 
     If cell.Rows.Hidden = False And _ 
     cell.Columns.Hidden = False And _ 
     cell.Value = "" Then 
      i = i + 1 
     End If 
    Next 
    VisibleBlankCells = i 
End Function 

然而,也有可能是關於更新和功能的一些問題:

  1. UDF的編輯被引用的範圍或調用其他的UDF後只更新值。因此,如果您在該範圍內隱藏了列或行,它將不會有即時效果
  2. 在Sub中的代碼的(工作)執行中,可見單元格(也)引用工作表中尚未使用的單元格「不可見」。然而,在我的解決方案中,所有未包含在隱藏行/列中的單元格都被視爲可見。
相關問題