Search This Blog

Wednesday 17 March 2010

Formulas based on cell formatting

From http://answers.google.com/answers/threadview/id/136528.html

1. In your Excel worksheet window, press Alt+F11.
2. In the new Microsoft Visual Basic window, click on the Insert menu,
Module.
3. In the right hand pane, in the window titled "Module1 (Code)",
paste in the following function:

Function SumBold(CellRange As Range)
    Dim sumb
    For Each cell In CellRange.Cells
        If cell.Font.Bold = True Then
            sumb = sumb + cell.Value
        End If
    Next
    SumBold = sumb
End Function

4. Press Alt+Q to save.

Now in any cell in this workbook, you can enter the formula =SumBold()
to have it add up all bolded numbers within a range.  You would use
=SumBold() in the exact way that you would use =SUM().

One caveat is that Excel does not appear to recognize bolding as an
event, so when you bold/unbold new items, the sum may not reflect the
new changes.  You'll have to use Ctrl+Alt+F9 to have it recalculate
all formulas on the sheet.
For italics it's virtually the same code.  Simply change the
following line from:
If cell.Font.Bold = True Then

And change it to:
If cell.Font.Italic = True Then

You'll also have to change the name of the function.  So for a Sum of
Italics, the code would look like:

Function SumItalics(CellRange As Range) 
    Dim sumi
    For Each cell In CellRange.Cells 
        If cell.Font.Italic = True Then 
            sumi = sumi + cell.Value 
        End If 
    Next 
    SumItalics = sumi
End Function