Style in Excel Add-in with step by step code example

Style in Excel Add-in with step by step code example

Cell Style

To apply several formats in one step, and to make sure that cells have consistent formatting, you can use a cell style. A cell style is a defined set of formatting characteristics, such as fonts and font sizes, number formats, cell borders, and cell shading. To prevent anyone from making changes to specific cells, you can also use a cell style that locks cells. In this article we will see how we can play with cell style using VSTO (Visual Studio Tools for Office) C# and VBA (Visual Basic for Applications)

Above image depicts available cell styles in Excel which can be customized as per specifications. User can also create its own style by clicking New Cell Style command. Also style can be merged using Merge Styles.

In this article we will see how we can dynamically apply styles in selected range. In this example we are applying “Accent1” style using code:

C# code example

private void btnCellStyle_Click(object sender, RibbonControlEventArgs e)
{
	//capture user selection
	excel.Range oRange = Globals.ThisAddIn.Application.Selection;
	oRange.Style = "Accent1";
}

Output

C# Remove Style

private void btnCellStyle_Click(object sender, RibbonControlEventArgs e)
{
	//capture user selection
	excel.Range oRange = Globals.ThisAddIn.Application.Selection;
	//Delete style
	oRange.Style.Delete
}

VBA Style code

Worksheets("Sheet2").Range("A1:A10").Style = "Percent"

VBA Style formatting

ThisWorkbook.Styles("Normal").Font.Bold = True

Above code will remove cell style from selected cell range. Please leave your valuable comments!!!

Next: insert new cell in Excel using VSTO C#

Leave a Reply

Your email address will not be published. Required fields are marked *