Excel VBA返回彩色单元格的最大值

我试图通过工作表创build一个函数并返回所有绿色(用户input颜色)彩色单元格的最高值。 我对VBA很陌生,除了“#VALUE!”之外,我不能输出任何东西。 这是我的代码看起来像:

Function ColorMax(Color As Integer) As Single Dim array1() Dim x As Integer Dim y As Integer Dim n As Integer n = 1 For x = 1 To 1000 For y = 1 To 1000 If Cells(x, y).Interior.ColorIndex = Color Then array1(n) = Cells(x, y).Value n = n + 1 End If Next Next ColorMax = Application.WorksheetFunction.max(array1) End Function 

有没有办法解决这个问题,以获得我想要的输出?

数组不是dynamic的,你必须设置尺寸的主动。

在这种情况下,不需要数组,它不会增加任何好处,只要testing它并在值更大时replacevariables:

 Function ColorMax(Color As Integer) As Single Dim x As Integer Dim y As Integer ColorMax = 0 With Application.Caller.Parent For x = 1 To 1000 For y = 1 To 1000 If Cells(x, y).Interior.ColorIndex = Color And .Cells(x, y).Value > ColorMax Then ColorMax = .Cells(x, y).Value End If Next Next End With End Function