Working with Shapes in Excel Addin C#

Working with Shapes in Excel Addin C#

Shapes:

Shapes represents floating objects which can be created within Excel worksheet. To insert a shape manually please follow steps:

  1. From the Insert tab, in the Illustrations group, click Shapes
  2. Select a shape by clicking on it
  3. Your cursor will change to a plus sign
  4. Click in your worksheet where you want to place the shape, drag your mouse until the shape is the size you want it to be, and then release your mouse

Let’s put some code around to create a textbox in Excel. Point to be noted, when it comes to handle shapes using code some coding standard automatically moves to shape programming as shown in blow code where the boolean property takes “msoTriState.msoTrue” inspite of “true“.

private void btnInsertTextBox_Click(object sender, RibbonControlEventArgs e)
{
	//retain selection
	excel.Worksheet oWorksheet = Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet;

	excel.Shape oShape= oWorksheet.Shapes.AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 249, 34, 141, 74);

	oShape.TextFrame2.TextRange.Characters.Text = "VBAOVERALL";
	oShape.TextFrame2.TextRange.Characters.Font.Bold = MsoTriState.msoTrue;
}

Prerequisites:

  • Visual Studio 2015 or above having Microsoft Office for Developer Tool installed
  • Create Excel Addin in C# code style (Visual Studio Tools for Office)
  • Create a ribbon designer and put button

Output:

Next : Header and Footer in Excel C#

Leave a Reply

Your email address will not be published.