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.

1 Answer 1

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
1
  • Can you please elaborate in what you did? Thanks! Nov 14, 2015 at 0:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.