Form controls in Excel Addin C#

Form controls in Excel Addin C#

Form Controls:

Form controls in Excel gives you a design base programming skill which you can drag and drop over the sheet and give a good look. In this article I will take you through form controls that you can create using VSTO C# code. First lets see how you can do it manually. Suppose you want to show case some choice based options to the user so user can make choice inspite of typing into cell “yes” or “no”.

  1. On the Developer tab, click Insert in the Controls group
  2. In the Form Controls group, click the Group Box button icon
  3. Click on the worksheet where you want to place the button
  4. Change the text by double clicking on it
  5. Now repeat the step 2-4 but select Option Button from the Form Controls inspite of group box as shown below

Let’s do some coding and see how we can get the same using VSTO C# in our Excel Addin

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 btnSymbol_Click(object sender, RibbonControlEventArgs e)
{
	//get active sheet reference
	excel.Worksheet oWorksheet = Globals.ThisAddIn.Application.ActiveSheet;

	//group box collection
	excel.GroupBoxes oGroupBoxes = oWorksheet.GroupBoxes();

	//Adding group box
	excel.GroupBox oGroupBox = oGroupBoxes.Add(298, 174, 162, 86);
	//Adding caption
	oGroupBox.Characters.Text = "Select Gender:";
	//Adding name to access control grammatically
	oGroupBox.Name = "grpBoxGender";
	
	//get collection
	excel.OptionButtons oOptionButtons= oWorksheet.OptionButtons();

	//add Male radio button
	excel.OptionButton oCheckBoxMale = oOptionButtons.Add(298, 184, 72, 72);
	//Adding caption text
	oCheckBoxMale.Characters.Text = "Male";
	//Adding name to access control grammatically
	oCheckBoxMale.Name = "rdoMale";

	//add Female radio button
	excel.OptionButton oCheckBoxFemale = oOptionButtons.Add(298, 204, 72, 72);
	//Adding caption text
	oCheckBoxFemale.Characters.Text = "Female";
	//Adding name to access control grammatically
	oCheckBoxFemale.Name = "rdoFemale";
}

Run the code and you will have same output as you got during manual stage above.

Next : Prevent user to rename sheet in Excel C#

Leave a Reply

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