How to draw and clear a border around a cell or range of cells

By Miguel Santos

This FAQ shows you how to draw and clear a border around a cell range. The sample code is in C# but can translated to VB.NET very easily.

This FAQ shows you how to draw and clear a border around a cell range.

The code assumes that you have defined Excel as:

using Excel=Microsoft.Office.Interop.Excel;

The code below will draw a thick border around the cells with the default line style and colour using the range method BorderAround.
         public void DrawThickBorderAround(Range cells)
        {
             cells.BorderAround(Type.Missing, Excel.XlBorderWeight.xlThick, Excel.XlColorIndex.xlColorIndexAutomatic, Type.Missing);
        }
You can easily make the code above to draw a border of any thickness bu adding border weigth as parameter.        
        

The code below will clear any border around the cells  using the range property Borders. Notice that you have to clear all edges and diagonals.
        public virtual void ClearThickBorderAround(Range cells)
        {
            Excel.Borders borders = cells.Borders;
             borders[Excel.XlBordersIndex.xlDiagonalUp].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
             borders[Excel.XlBordersIndex.xlDiagonalDown].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
             borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
             borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
             borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
             borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
        }

The sample code is presented in C# but it is easy to translate it to VB.NET.


How to draw and clear a border around a cell or range of cells  (9209 Views)