Most Valuable Professional


View Jan Karel Pieterse's profile on LinkedIn subscribe to rss feed
Subscribe in a reader

Audit !!!

Check out our RefTreeAnalyser
the ultimate Excel formula auditing tool.

Speed up your file

FastExcel
The best tool to optimise your Excel model!
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 45 in total (Show All Comments):

 


Comment by: Jan Karel Pieterse (8/15/2013 8:12:29 AM)

Hi Doug,

On which line does the error occur?

I don't have a MAC, so this question is hard to answer!

 


Comment by: Doug (8/15/2013 9:11:09 PM)

OK - Resolved the syntax error by pasting the script in Word Wrangler and resetting the indentation -- then pasting it through to VB (for some reason the VB editor didn't like the cut and paste directly from the web page?)

Now I'm getting a 'subscript out of range error' on this line:

    Set oStylesh = ThisWorkbook.Worksheets("Config - Styles")

Any idea why?

 


Comment by: Jan Karel Pieterse (8/16/2013 3:42:09 PM)

Hi Doug,

apparently you do not have a worksheet names 'Config - Styles'

 


Comment by: Doug (2/2/2014 4:00:01 PM)

I've been using the ListStyles script and find it quite useful. I had resolved my earlier syntax error by:

1. adding a line before the Set statement:
Worksheets.Add().Name = "Config - Styles"

2. switching
ThisWorkbook
to
ActiveWorkbook
, (as the sub is in Personal.xls)

so I now have a one-click macro to list styles in any workbook.

My Question: Is it possible to modify the script so that it only lists styles that have been used (applied) and not all styles in the workbook? (or should I ask the question on Eileen's lounge?)

Thanks for some great tools!

 


Comment by: Jan Karel Pieterse (2/2/2014 9:35:37 PM)

Hi Doug,

Unfortunately, what it takes is run thrugh all cells in your file and get their style. Then check that list against the list of styles t find out the unused ones. Very slow.

 


Comment by: Rudra (4/18/2014 10:25:29 AM)

To list Styles

Sub ListAllStyles()
Dim MyStyle As Style
Dim MyRow As Integer

MyRow = 1
For Each MyStyle In ThisWorkbook.Styles
     With Cells(MyRow, 1): .Value = MyStyle.Name: .Style = MyStyle.Name: End With
    MyRow = MyRow + 1
Next
    
End Sub

 


Comment by: Andy Kingston (4/24/2014 9:53:47 AM)

Hi JKP,

I have a worksheet formatted with a lot of cell styles, which I want to copy into another workbook, which also uses (different) cell styles.

I don't want the cell styles to be copied across to the workbook, but I would like the worksheet to retain its formatting (i.e. look the same but without styles)

Is there a way to deviate each cell on a sheet from it's style?... I can then remove all styles from the worksheet before copying into the workbook

NB: I've had some limited success with:

select all > increase font size and select all > italicize followed by select all > decrease font size and select all > de-italicize

...as this seems to deviate the number formats and fonts etc, but the fill colours / outline still get scrapped if I then remove all cell styles.

 


Comment by: Jan Karel Pieterse (4/28/2014 10:14:31 AM)

Hi Andy,

I don't really know. I would probably write some code that does a copy, paste special Values (or formulas, whichever is needed) and then loop through the cells to set their style names to match the source cells style names.

 


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].