【问题标题】:Excel VBA Return Max Value of Colored CellExcel VBA返回彩色单元格的最大值
【发布时间】:2018-02-08 17:08:50
【问题描述】:

我正在尝试创建一个函数,遍历工作表并返回所有绿色(用户输入颜色)彩色单元格的最大值。我对 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

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

【问题讨论】:

  • 你没有设置数组大小所以它是空的。

标签: arrays vba excel background-color


【解决方案1】:

数组不是动态的,您必须以编程方式设置大小。

在这种情况下不需要数组,它没有任何好处,只需测试它并如果值更大则替换变量:

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

【讨论】:

  • 赞成使用Application.Caller.Parent引用工作表的技术
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-29
  • 1970-01-01
相关资源
最近更新 更多