Export (0) Print
Expand All

How to: Apply Styles to Ranges in Workbooks

Updated: July 2008

Applies to

The information in this topic applies only to the specified Visual Studio Tools for Office projects and versions of Microsoft Office.

Project type

  • Document-level projects

  • Application-level projects

Microsoft Office version

  • Excel 2003

  • Excel 2007

For more information, see Features Available by Application and Project Type.

You can apply named styles to regions in workbooks. Excel supplies a number of predefined styles.

The Format Cells dialog box displays all the options you can use to format cells, and each of these options is available from your code. To display this dialog box in Excel, click Cells on the Format menu.

To apply a style to a named range in a document-level customization

  1. Create a new style and set its attributes.

    Excel.Style style = Globals.ThisWorkbook.Styles.Add("NewStyle", missing);
    
    style.Font.Name = "Verdana";
    style.Font.Size = 12;
    style.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
    style.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Gray);
    style.Interior.Pattern = Excel.XlPattern.xlPatternSolid;
    
  2. Create a NamedRange control, assign text to it, and then apply the new style. This code must be placed in a sheet class, not in the ThisWorkbook class.

    Microsoft.Office.Tools.Excel.NamedRange rangeStyles =
        this.Controls.AddNamedRange(this.Range["A1", missing], "rangeStyles");
    
    rangeStyles.Value2 = "'Style Test";
    rangeStyles.Style = "NewStyle";
    rangeStyles.Columns.AutoFit();
    

To apply a style to a named range in an application-level add-in

  1. Create a new style and set its attributes.

    Excel.Style style = this.Application.ActiveWorkbook.Styles.Add("NewStyle", missing);
    
    style.Font.Name = "Verdana";
    style.Font.Size = 12;
    style.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
    style.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Gray);
    style.Interior.Pattern = Excel.XlPattern.xlPatternSolid;
    
  2. Create a Range, assign text to it, and then apply the new style.

    Excel.Range rangeStyles = this.Application.get_Range("A1", missing);
    
    rangeStyles.Value2 = "'Style Test";
    rangeStyles.Style = "NewStyle";
    rangeStyles.Columns.AutoFit();
    

Date

History

Reason

July 2008

Added a code example that can be used in an application-level add-in.

Customer feedback.

Community Additions

ADD
Show:
© 2014 Microsoft