Excel VBA - 突出显示已汇总的单元格

时间:2015-06-28 23:13:29

标签: excel-vba sum vba excel

我有一张Excel工作表,其中多个值汇总形成总计。然后我必须手动检查每个总数是否正确。一旦值合计,我想突出显示单个单元格并对它们进行颜色编码。我想出了如何通过宏为Excel中的单元格着色。有没有办法弄清楚从公式中总结了哪些细胞?

例如;
如果求和值= A1 + A4 + A7,则宏应对这些单元格进行颜色编码。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

这可能会给你一个想法。以下代码将为所选单元格的所有直接先例着色为浅绿色。例如,在A10中我有公式

=A1+A4+A7

如果在选择A10时调用以下宏,则A1,A4和A7显示为绿色:

Sub ColorSummands()
    Dim R As Range
    Set R = Selection
    R.DirectPrecedents.Interior.Color = 5296274 'light green
End Sub

修改代码很容易,弹出一个输入框,要求用户选择颜色

答案 1 :(得分:0)

如果以下VBA代码适合您,请告诉我。 它允许您突出显示任何工作表中的任何单元格(只要它在同一工作簿中)。它可以帮助您进行加,减,乘或除 - 它甚至可以同时处理几个公式单元格。

Sub color_cells_in_formula()

Dim workrng As Range

Dim lcolor As Long

   Set workrng = Application.Selection

   Set workrng = Application.InputBox("Range", xTitleId, workrng.Address, Type:=8)

If Application.Dialogs(xlDialogEditColor).Show(10, 0, 125, 125) = True Then

  lcolor = ActiveWorkbook.Colors(10)

Else

End If

For Each cell In workrng

If cell.Value <> "" Then

   Dim result As String

   result = cell.Formula

   result = Replace(result, "(", "   ")

   result = Replace(result, ")", "   ")

   result = Replace(result, "-", "   ")

   result = Replace(result, "+", "   ")

   result = Replace(result, "*", "   ")

   result = Replace(result, "/", "   ")

   result = Replace(result, "=", "   ")

   result = Replace(result, ",", "   ")

   Dim cells() As String

   cells = Split(Trim(result), "   ")

   For j = 0 To UBound(cells)

    Range(cells(j)).Interior.Color = lcolor

   Next j

End If

Next cell

End Sub