【问题标题】:Calculation of values based on the color of cells in Excel VBA基于Excel VBA中单元格颜色的值计算
【发布时间】:2018-09-09 18:49:19
【问题描述】:

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

 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)"

【问题讨论】:

  • 因此您需要独立检查 H:U 中每一列中的每个单元格。使用 UDF 可能更好。 “颜色”是手动设置的还是条件格式的?
  • 颜色是预先设置好的。 UDF 代表什么?感谢您的努力。
  • “颜色”是手动设置还是条件格式?
  • 它们是条件格式的。

标签: colors formula average calculation


【解决方案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

【讨论】:

  • 为了清晰起见,我刚刚上传了一张图片。谢谢你的代码,我明天试试。非常感谢
  • 您将必须准确确定您在 CFR 中使用的绿色阴影。可以是 vbGreen,可以是 RGB(146, 208 , 80),也可以是其他。
  • 我用过“vbGreen”。谢谢
  • 嗨 Jeeped,代码运行良好。但是,我希望将公式包含在单元格中,而不仅仅是计算值。我试过这个:.Cells(104, c).Formula = "= Average(rng)",但效果不大
  • 您不能直接在工作表公式中使用 vba 范围。但是,您可以使用它的地址。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 2019-02-15
  • 2018-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多