根据 Excel VBA 中单元格的颜色计算值
Calculation of values based on the color of cells in Excel VBA
该代码显示了基于定义的单元格中的值的简单平均计算。这些单元格以三种颜色突出显示。目的是将这些值纳入计算中,例如单元格颜色是什么。绿色。我知道 "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 循环遍历每一列。循环遍历每一列中的每个单元格。构建绿色单元格的并集并平均该并集。移至下一栏。
没有必要为每一列构建公式,因为任何更改都需要重新运行子过程。这些将适用于手动设置和条件格式的单元格颜色。
.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
该代码显示了基于定义的单元格中的值的简单平均计算。这些单元格以三种颜色突出显示。目的是将这些值纳入计算中,例如单元格颜色是什么。绿色。我知道 "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 循环遍历每一列。循环遍历每一列中的每个单元格。构建绿色单元格的并集并平均该并集。移至下一栏。
没有必要为每一列构建公式,因为任何更改都需要重新运行子过程。这些将适用于手动设置和条件格式的单元格颜色。
.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