2012-08-16 136 views
0

我有以下VBA函數:Excel的VBA:返回計算結果的單元格值

Function IndexOfColor(InRange As Range, ColorIndex As Long) As Excel.Range 
Dim R As Range 

Application.Volatile True 
If IsValidColorIndex(ColorIndex) = False Then 
    IndexOfColor = 0 
    Exit Function 
End If 

For Each R In InRange.Cells 
    If R.Interior.ColorIndex = ColorIndex Then 
     IndexOfColor = R 
     Exit Function 
    End If 
Next R 

IndexOfColor = 0 
End Function 

在我的excel表,我稱之爲:

=IndexOfColor(D15:M24,37) 

,一定可以得到"#VALUE"。我已經調試過該功能,直到最後,並且沒有問題。雖然這應該只返回1結果(我正在查看範圍,並且只有一個彩色單元格),但我也嘗試將此數組結果(CTRL-SHIFT-ENTER)。

對此提出建議?

+0

什麼是CI取代Variant?它不應該是'ColorIndex'嗎? – 2012-08-16 13:05:47

+0

'雖然這應該只返回1結果'也是'1'你是如何到達的?該函數應該返回一個範圍')作爲Excel.Range'?也許如果你能夠準確地解釋你想做什麼? – 2012-08-16 13:07:49

+0

我看到你的函數定義了兩個參數'InRange'和'ColorIndex',但我看到你用3個參數調用函數'D15:M24','37'和'0' – SeanC 2012-08-16 13:10:01

回答

1

這是你正在嘗試?如果細胞不會有小數,那麼你可以用Long

Function IndexOfColor(InRange As Range, ColorIndex As Long) As Variant 
    Dim R As Range 

    IndexOfColor = 0 

    On Error GoTo Whoa 

    Application.Volatile True 

    If Not IsValidColorIndex(ColorIndex) = False Then 
     For Each R In InRange.Cells 
      If R.Interior.ColorIndex = ColorIndex Then 
       IndexOfColor = R.Value 
       Exit For 
      End If 
     Next R 
    End If 
Whoa: 
End Function 
+0

「As Long」就是我一直在尋找的東西。實際上,我之前有過這個,但被格式錯誤所矇蔽,所以認爲這個數字是某種指針。 – Jahmic 2012-08-17 11:01:24