0

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.

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

1 Answers1

0

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
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862