C




Excel C# - hiding rows / columns programmatically

David Robertson
WRITTEN BY  David Robertson- 26 October 2011

I have been writing an Add-in for Excel with some functionality related to the hiding of rows and columns depending on certain criteria. I ran into a problem where the spreadsheet hung at 99% on every 2nd recalculation.

The following code samples show the before and after for the problem / solution to the issue at hand. There is no denying that it is a simple fix, and one might think quite intuitive, but it took me a while to find it and would like to share with the community.

Code Sample Before Fix:

///
/// Hide the row
///
((Excel.Range)loWorkSheet.Cells[lnRow + lnRowOffset, 1]).EntireRow.Hidden = false;
///
/// Hide the column
///
((Excel.Range)loWorkSheet.Cells[Type.Missing, lnColumn]).EntireColumn.Hidden = false;

Code Sample After Fix:

///
/// Hide the row
///
if ((bool)((Excel.Range)loWorkSheet.Cells[lnRow + lnRowOffset, 1]).EntireRow.Hidden)
{
    ((Excel.Range)loWorkSheet.Cells[lnRow + lnRowOffset, 1]).EntireRow.Hidden = false;
}
            
///
/// Hide the column
///
if ((bool)((Excel.Range)loWorkSheet.Cells[Type.Missing, lnColumn]).EntireColumn.Hidden)
{
    ((Excel.Range)loWorkSheet.Cells[Type.Missing, lnColumn]).EntireColumn.Hidden = false;
}
            

Essentially what this fix is doing is checking to see if the row / column is hidden in the first place and then applying a CHANGE rather than reapplying the same value to the EntireRow / Column property.

Bookmark and Share
Write Your Comment
  • Captcha image


© 2012 D.A.R. Enterprises. All rights reserved.

Powered By D.A.R. Enterprises

webmaster@dare-it.co.uk