Rotate Shape in Excel Addin C#

Rotate:

VSTO offers IncrementRotation method which takes float value to rotate the shape. In this article I will cover two use-cases as follow:

  1. Dynamically get selected shape name
  2. Rotate Shape based on user input

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

Code example:

private void btnRotateShape_Click(object sender, RibbonControlEventArgs e)
{
	//get active worksheet reference
	excel.Worksheet oWorksheet = Globals.ThisAddIn.Application.ActiveSheet;
	
	//Retain selection
	object oSelection = (object)Globals.ThisAddIn.Application.Selection;
	
	//get selected shape name
	string shapeName=oSelection.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, oSelection, null).ToString();
	
	//Retain all available shapes in worksheet
	excel.Shapes oShapes = oWorksheet.Shapes;
	
	//Get selected shape object
	excel.Shape oShape = oShapes.Item(shapeName);
	
	//take user input to rotate shape
	var shapeRotationValue = Globals.ThisAddIn.Application.InputBox("Enter value to rotate shape:", "Shape Rotation", 0);
	
	//Rotate shape
	oShape.IncrementRotation(Convert.ToDouble(shapeRotationValue));
}

Output:

Now try click on OK button and you will see output as shown in below screenshot

Next : Add custom validation in a Range using Excel C#

Leave a Reply

Your email address will not be published.