Autofit Row Height Excel Addin VSTO C#

Autofit Row Height Excel Addin VSTO C#

AutoFit:

There might be a case where you copied data from some other sources and pasted in Excel Sheet. Ah!!! you realize lots of rows height is messed unnecessary and you are end up with unwanted formatting. You have various options to fix it but if you are aware of those else you will have to crawl each row and adjust the height. Let’s give it a try using VSTO C# code, which will do magic for your and fix it up.

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 btnAutoFitRowHeight_Click(object sender, RibbonControlEventArgs e)
{
	//Get Sheet reference
	excel.Worksheet oWorksheet = Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet;
	//retain active row selection
	excel.Range oRange = Globals.ThisAddIn.Application.Selection;
	oRange.Rows.AutoFit();
}

In above code I have called AutoFit method of Rows collection object which will make sure to fit my row height based on content in selected range.

Before code execution:

Post code execution:

Please leave your valuable comments!!!

Next : Dynamically change column width in Excel c#

Leave a Reply

Your email address will not be published.