Dynamically change ColumnWidth in Excel C# Addin

Dynamically change ColumnWidth in Excel C# Addin

ColumnWidth:

ColumnWidth property let you handle width of columns in a selection. The parent Range object exposes ColumnWidth property which takes double type value and expand/shrink columns based on supplied size. In this article we will be writing code to change column width based on user inputs dynamically.

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 btnColumnWidth_Click(object sender, RibbonControlEventArgs e)
{
	//retain selected columns selection
	excel.Range oRange = Globals.ThisAddIn.Application.Selection;
	//Show popup to grab input height from using
	var userValue = Globals.ThisAddIn.Application.InputBox("Enter column width:", "Adjust column width", 15.75);
	//declare variable to get through out
	double oValue;
	//check if user has given valid input
	if (double.TryParse(userValue.ToString(), out oValue))
	{
		//Set rowheight property by converting user value
		oRange.ColumnWidth = Convert.ToDouble(userValue);
	}
}

Above code is using an InputBox which is a custom dialog to grab the input, then we put a check to validate if user dismisses the InputBox by hitting Cancel button (On Cancel InputBox returns boolean “false“). On OK button we will set ColumnWidth property by putting explicit conversion.

Before executing code:

After code execution:

Above screenshot depicts input and finally on clicking OK button, the result will look like as follow:

Next : Dynamically autofit column width using Excel C#

Leave a Reply

Your email address will not be published.