Search code examples
c#excel-interopmemory-efficientnamed-ranges

How can I efficiently add right borders to an Excel range with C#?


Is there a concise (one-line) way to programatically add right borders to a range of cells on an Excel spreadsheet using C#?

This code works:

private void AddRightBorderToMainRange()
{
    for (int i = COLUMN_HEADING_ROW; i < _lastRowAdded; i++)
    {
        for (int j = ITEMDESC_COL; j < TOTALS_COL; j++)
        {
            var rightBorderizeRange = _xlSheet.Range[_xlSheet.Cells[i, j], _xlSheet.Cells[i, j]];
            Borders border = rightBorderizeRange.Borders;
            border[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
        }
    }
}

...(outer for loop covering the row range, inner loop covering the column range), but seems like overkill and probably inefficient.


Solution

  • This is a little more efficient and less crosseye-inducing:

    var rightBorderizeRange = 
        _xlSheet.Range[_xlSheet.Cells[COLUMN_HEADING_ROW, ITEMDESC_COL], 
        _xlSheet.Cells[_lastRowAdded, TOTALS_COL]];
    Borders border = rightBorderizeRange.Borders;
    border[XlBordersIndex.xlInsideVertical].LineStyle =
        XlLineStyle.xlContinuous;
    

    So what needs to be done is:

    0) Define the range you want to operate on (add right borderlines to) - named *rightBorderizeRange* above
    1) Get the Borders member for that range - named *border* above
    2) Apply a border to the InsideVertical (vertical lines within that range) member of the border array