简体   繁体   中英

Excel VBA - Highlight cell that have been summed

I have an Excel sheet where several values get summed to form totals. I then have to manually check if each total is correct. As soon as the values are totaled, I want to highlight the individual cells and color code them. I figured out how to color code cells in excel through a macro. Is there a way to figure out which cells have been summed from the formula?

For example;
If the summed value = A1 + A4 + A7, the macro should color code these cells.

Any help is much appreciated.

This might give you an idea. The following code will color all direct precedents of the selected cell light green. For example, in A10 I have the formula

=A1+A4+A7

If I invoke the following macro while A10 is selected then A1,A4 and A7 are colored green:

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

It would be easy enough to modify the code so that an inputbox pops up asking for the user to pick the color

Let me know if the following VBA code works for you. It will allow you to highlight any cell in any worksheet (as long it's in the same workbook). It can help you with add, subtract, multiply or division - and it can even work on several formula cells at once.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM