I am trying to create a simple function that will add borders around every cell in a certain range. Using the wonderful recording this generates a ton of code which is quite
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
You only need a single line of code to set the border around every cell in the range:
Range("A1:F20").Borders.LineStyle = xlContinuous
It's also easy to apply multiple effects to the border around each cell.
For example:
Sub RedOutlineCells()
Dim rng As Range
Set rng = Range("A1:F20")
With rng.Borders
.LineStyle = xlContinuous
.Color = vbRed
.Weight = xlThin
End With
End Sub
The following can be called with any range as parameter:
Option Explicit
Sub SetRangeBorder(poRng As Range)
If Not poRng Is Nothing Then
poRng.Borders(xlDiagonalDown).LineStyle = xlNone
poRng.Borders(xlDiagonalUp).LineStyle = xlNone
poRng.Borders(xlEdgeLeft).LineStyle = xlContinuous
poRng.Borders(xlEdgeTop).LineStyle = xlContinuous
poRng.Borders(xlEdgeBottom).LineStyle = xlContinuous
poRng.Borders(xlEdgeRight).LineStyle = xlContinuous
poRng.Borders(xlInsideVertical).LineStyle = xlContinuous
poRng.Borders(xlInsideHorizontal).LineStyle = xlContinuous
End If
End Sub
Examples:
Call SetRangeBorder(Range("C11"))
Call SetRangeBorder(Range("A" & result))
Call SetRangeBorder(DT.Cells(I, 6))
Call SetRangeBorder(Range("A3:I" & endRow))
Here's another way
Sub testborder()
Dim rRng As Range
Set rRng = Sheet1.Range("B2:D5")
'Clear existing
rRng.Borders.LineStyle = xlNone
'Apply new borders
rRng.BorderAround xlContinuous
rRng.Borders(xlInsideHorizontal).LineStyle = xlContinuous
rRng.Borders(xlInsideVertical).LineStyle = xlContinuous
End Sub
For adding borders try this, for example:
Range("C11").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("A15:D15").Borders(xlEdgeBottom).LineStyle = xlContinuous
Hope that syntax is correct because I've done this in C#.
I have a set of 15 subroutines I add to every Coded Excel Workbook I create and this is one of them. The following routine clears the area and creates a border.
Sample Call:
Call BoxIt(Range("A1:z25"))
Subroutine:
Sub BoxIt(aRng As Range)
On Error Resume Next
With aRng
'Clear existing
.Borders.LineStyle = xlNone
'Apply new borders
.BorderAround xlContinuous, xlThick, 0
With .Borders(xlInsideVertical)
.LineStyle = xlContinuous
.ColorIndex = 0
.Weight = xlMedium
End With
With .Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.ColorIndex = 0
.Weight = xlMedium
End With
End With
End Sub