Most Valuable Professional


View Jan Karel Pieterse's profile on LinkedIn subscribe to rss feed

Subscribe in a reader

Subscribe to our mailing list

* indicates required
Newsletter Archive

Audit !!!

Check out our RefTreeAnalyser
the ultimate Excel formula auditing tool.

Events


Excel VBA for Financials (Dutch)

Third party tools

Speed up your file

FastExcel
The best tool to optimise your Excel model!

Repair your file

Stellar Phoenix Excel Repair
Best tool to repair corrupt Excel sheets and objects
Home > English site > Articles > Styles in Excel > VBA Examples
Deze pagina in het Nederlands

Styles in Excel

VBA examples and tools

The little VBA routines shown below will greatly easy your work with styles. As an important side effect, these also show you how the style object works in VBA.

Find cells with a certain style

This routine find cells with a style containing "demo" in its name:

Sub FindaStyle()
    Dim oSh As Worksheet
    Dim oCell As Range
    For Each oSh In ThisWorkbook.Worksheets
        For Each oCell In oSh.UsedRange.Cells
            If oCell.Style Like "*demo*" Then
                Application.GoTo oCell
                Stop
            End If
        Next
    Next
End Sub

As soon as a cell is encountered with a style that matches that name filter, the code stops (Stop) and you can check out the cell in detail.

Creating a list of styles

This sub adds a table of your styles on a worksheet named "Config - Styles":

Sub ListStyles()
    Dim oSt As Style
    Dim oCell As Range
    Dim lCount As Long
    Dim oStylesh As Worksheet
    Set oStylesh = ThisWorkbook.Worksheets("Config - Styles")
    With oStylesh
        lCount = oStylesh.UsedRange.Rows.Count + 1
        For Each oSt In ThisWorkbook.Styles
            On Error Resume Next
            Set oCell = Nothing
            Set oCell = Intersect(oStylesh.UsedRange, oStylesh.Range("A:A")).Find(oSt.Name, _
                oStylesh.Range("A1"), xlValues, xlWhole, , , False)
            If oCell Is Nothing Then
            lCount = lCount + 1
            .Cells(lCount, 1).Style = oSt.Name
            .Cells(lCount, 1).Value = oSt.NameLocal
            .Cells(lCount, 2).Style = oSt.Name
            End If
        Next
    End With
End Sub

Clear all formatting of cells and re-apply their styles

The code below removes all formatting of all cells and subsequently re-applies their style to them.

Watch out: if you have not adhered to using styles strictly, you will loose all formatting in your file!!!

Sub ReApplyStyles()
'Resets styles of cells to their original style (resets all formatting done on top of ANY style)
    Dim oCell As Range
    Dim oSh As Worksheet
    If MsgBox("Proceed with care:" & vbNewLine & vbNewLine & _
              "This routine will erase all formatting done on top of the existing cell styles." & vbNewLine & _
              "Continue?", vbCritical + vbOKCancel + vbDefaultButton2, GSAPPNAME) = vbOK Then
        For Each oSh In ActiveWindow.SelectedSheets
            For Each oCell In oSh.UsedRange.Cells
                If oCell.MergeArea.Cells.Count = 1 Then
                    oCell.Style = CStr(oCell.Style)
                End If
            Next
        Next
    End If
End Sub

Replace one style with another

The code below uses a list with two columns. The column on the left contains the names of existing styles. The column to its immediate right contains the names of the style you want to replace them with.

The code will run through the selected cells in the left column and check if the style name in the column to its right differs. If so, it will prompt you with the alternative name. Clicking OK will cause the code to update ALL cells to which the old style was applied to the new style. Before running this sub you need to select the cells in the left hand column.

Sub FixStyles()
'-------------------------------------------------------------------------
' Procedure : FixStyles
' Company   : JKP Application Development Services (c)
' Author    : Jan Karel Pieterse
' Created   : 4-10-2007
' Purpose   : Replaces styles with the replacement style as defined by a two column list.
'             column 1 should contain the existing style, col 2 the replacing style
'-------------------------------------------------------------------------
    Dim sOldSt As String
    Dim sNewSt As String
    Dim oSh As Worksheet
    Dim oCell As Range
    Dim oSourceCell As Range
    Set oSourceCell = ActiveCell
    While oSourceCell.Value <> ""
        sOldSt = oSourceCell.Value
        sNewSt = InputBox("Please enter replacement style for:" & sOldSt, "Style changer", oSourceCell.Offset(, 1).Value)
        If sNewSt = "" Then Exit Sub
        If sNewSt <> "" And sNewSt <> sOldSt Then
            For Each oSh In ThisWorkbook.Worksheets
                For Each oCell In oSh.UsedRange
                    If oCell.Style = sOldSt Then
                        Application.GoTo oCell
                        On Error Resume Next
                        oCell.Style = sNewSt
                    End If
                Next
            Next
        End If
        Set oSourceCell = oSourceCell.Offset(1)
    Wend
End Sub

Removing formating from an Excel Table

Suppose you have just converted a range to a table (see this article), but the range had some formatting set up such as background fills and borders. Tables allow you to format things like that automatically, but now your preexisting formatting messes up the table formatting. One way to overcome this is by changing the style of the cells in the table back to the Normal style. This however removes your number formats too. The little macro below fixes that by first making a copy of the normal style, setting its Number checkbox to false and then applying the new style without number format to the table. Finally it applies the tablestyle and deletes the temporary style:

Sub RemoveFormattingOfTable()
    Dim oStNormalNoNum As Style
    On Error Resume Next
    Set oStNormalNoNum = ActiveWorkbook.Styles("NormalNoNum")
    On Error GoTo 0
    If oStNormalNoNum Is Nothing Then
        ActiveWorkbook.Styles.Add "NormalNoNum"
        Set oStNormalNoNum = ActiveWorkbook.Styles("NormalNoNum")
        oStNormalNoNum.IncludeNumber = False
    End If
    With ActiveSheet.ListObjects(1)
        .Range.Style = "NormalNoNum"
        'Now apply tablestyle:
        .TableStyle = "TableStyleLight1"
    End With
    ActiveWorkbook.Styles("NormalNoNum").Delete
End Sub

 


 


Comments

Showing last 8 comments of 48 in total (Show All Comments):

 


Comment by: AlexJ (2/6/2009 6:24:31 AM)

Are we going to see a "Style Manager" application from you in future, Jan Karel?

 


Comment by: Jan Karel Pieterse (2/6/2009 6:56:08 AM)

Hi Alex,

I have given that some serious thought. But this is quite a task, so I wouldn't hold your breath :-)

 


Comment by: Bob Phillips (2/19/2009 5:20:30 PM)

I have written a Style Manager addin to go with an app I am writing that has heavy style usage. I needed as the builtin styles dialog is rubbsih, I needed to see all the styles, delete them easily, rename them, adopt a style, get a preview of the style and so on.

One of the big problems with styles in VBA is the lack of methods exposed, copying a style is not simple, you have to add a style based upon a cell. So you identify a cell with that style, or set that set to a style, and then add the style based upon that cell. You cannot create a style based upn another style. And the only other option is merge a workbook styles colletion, all of them.

Copying a style across workbooks is not straightforward.

 


Comment by: Jan Karel Pieterse (2/20/2009 5:08:18 AM)

Hi Bob,

Sounds good. I can't wait to see it published!

 


Comment by: Jörgen Möller (1/13/2010 6:09:52 AM)

Here is a developed version of your "FindaStyle", I wanted to be able to have it selecting all cells with a certain style.

So this goes through the active workbook sheet by sheet and selects all cells with a defined style.

Sub StyleFindAll()
'Jörgen Möller Jan 13, 2010
    Dim oSh As Worksheet, oCell As Range, sStyle As String, oStyleCells As Range, i As Long
    sStyle = InputBox("What Style (or part of style name) to look for?", "Style Find", "Currency")
    If sStyle <> "" Then sStyle = "*" & sStyle & "*" Else Exit Sub
    For Each oSh In ActiveWorkbook.Worksheets
        i = 0
        For Each oCell In oSh.UsedRange.Cells
            If oCell.Style Like sStyle Then
                If i > 0 Then
                    Set oStyleCells = Application.Union(oStyleCells, oCell)
                Else
                    Set oStyleCells = oCell
                End If
                i = i + 1
            End If
        Next oCell
        If i > 0 Then
            oSh.Activate
            oStyleCells.Select
        End If
    Next oSh
End Sub


Feel free to put it on the website.
Regards
Jörgen

 


Comment by: Jan Karel Pieterse (1/13/2010 6:12:57 AM)

Hi Jörgen,

Thanks for the code!

 


Comment by: Jamie (3/20/2010 8:53:48 AM)

I want to count how many orange cells I have in a column, how can I do this?

 


Have a question, comment or suggestion? Then please use this form.

If your question is not directly related to this web page, but rather a more general "How do I do this" Excel question, then I advise you to ask your question here: www.eileenslounge.com.

Please enter your name (required):

Your e-mail address (optional but if you want me to respond it helps!; will not be shown, nor be used to send you unsolicited information):

Your request or comment:

To post VBA code in your comment, use [VB] tags, like this: [VB]Code goes here[/VB].