2017-03-16 62 views
0

不知道我在做什麼錯在這裏。我試圖創建一個函數,該函數在調用時計算輸入範圍中具有該特定RGB顏色的所有非空單元。我嘗試在我的工作簿中使用該功能,但是我獲得#NAME?而不是一個數字作爲回報。功能在VBA

Function countProspect(rng1 As Range, rng2 As Range) As Long 

Dim cel As Variant 

countProspect = 0 
For Each cel In Range(rng1, rng2) 
    If cel.Interior.Color = RGB(248, 203, 173) And IsEmpty(cel.Value) = False Then 
     countProspect = countProspect + 1 
    End If 
Next cel 

End Function 
+2

*此代碼的*號是?它是在一個標準模塊中(它應該在哪裏)或者像Sheet 1代碼模塊(它不應該在那裏)? –

+1

適用於我,如果它在正確的地方。 – YowE3K

+3

你好嗎? '= countProspect(A1,A10)'或'= countProspect(A1:A10)'?它是爲第一個版本編寫的,不會與第二個版本一起工作。這對UDF來說很不尋常。 –

回答

1

如果你想讓你的代碼支持不同大小的範圍的單或雙輸入,應該這樣做。最好使用範圍,而不僅僅是2個單元格,因爲函數不會在兩個單元格之間發生更改時更新。

例如如果您有一個單元=countProspect(A3,C10),更改爲B4將不會更新爲B4未使用通過countProspect。你需要考慮這一點,否則你會得到不準確的結果。

Option Explicit 

Function countProspect(rng1 As Range, Optional rng2 As Range) As Long 
    Dim allCell As Range, cel As Range, count As Long 

    Set allCell = rng1 
    If Not rng2 Is Nothing Then Set allCell = Union(allCell, rng2) 
    For Each cel In allCell.Cells 
     If cel.Interior.Color = RGB(248, 203, 173) And Not IsEmpty(cel) Then 
      count = count + 1 
     End If 
    Next cel 
    countProspect = count 
End Function