根据Excel VBA中单元格的颜色计算值

时间:2018-09-09 18:49:19

标签: colors formula average calculation

代码显示了基于所定义单元格中的值的简单平均计算。这些单元格以三种颜色突出显示。目的是将这些值用于计算哪个单元格颜色是例如绿色。我知道需要“如果”命令,我只是不知道将其放在哪里:

enter image description here

 Dim wb As Workbook, wq As Object
 Dim ws As Worksheet, datdatum
 Dim cell As Range, cell2 As Range, col As Long


 ws.Range("H104:U104").Formula = "= Average(H34,H39,H68,H71,H83)"

1 个答案:

答案 0 :(得分:1)

我假设整个行不是绿色,并且每一列都需要独立查看。

从H到U遍历每一列。遍历每一列中的每个单元格。建立绿色单元的联合,然后对联合进行平均。移至下一列。

为每列构建公式没有意义,因为任何更改都需要重新运行子过程。这些将同时适用于手动设置和条件格式的单元格颜色。

.DisplayFormat在用户定义函数中不起作用。

dim c as long, r as long, rng as range

with worksheets("sheet1")

    for c =8 to 21
        for r=2 to 103
            if .cells(r, c).displayformat.interior.color = vbgreen then
                if rng is nothing then
                    set rng = .cells(r, c)
                else
                    set rng = union(rng, .cells(r, c))
                end if
            end if
        next r

        if not rng is nothing then _
            .cells(104, c) = application.average(rng)
        'alternate
        'if not rng is nothing then _
            '.cells(104, c).formula = "=average(" & rng.address(0,0) & ")"
    next c

end with

替代

dim c as long

with worksheets("sheet1")
    if .autofiltermode then .autofiltermode = false

    for c =8 to 21
        with .range(.cells(1, c), .cells(103, c))
            .AutoFilter Field:=1, Criteria1:=vbgreen, Operator:=xlFilterCellColor
            .cells(104, c) = application.subtotal(101, .cells)
            .AutoFilter
        end with
    next c

end with