excel set borders for range vba code example

Example 1: excel vba set range borders like grid

'VBA routine to set the grid borders THROUGHOUT a range:

Sub SetRangeGrid(r As Range, Optional stl = 1, Optional clr = 0, Optional wgt = 2)
    With r.Borders()
        .LineStyle = stl
        .Color = clr
        .Weight = wgt
    End With
End Sub

'--------------------------------------------------------------------

SetRangeBorder [d2:k10]
SetRangeBorder [d2:k10], vbRed
SetRangeBorder [d2:k10], , xlThick

Example 2: excel vba set border around range

'VBA routine to set the border AROUND or THROUGH a range:

Sub SetRangeBorders(r As Range, Optional edges As Boolean = 1, Optional stl = 1, Optional clr = 0, Optional wgt = 2)
    Dim e
    If edges Then
        For Each e In Array(xlEdgeLeft, 8, 9, 10)
            SetBorder r.Borders(e), stl, clr, wgt
        Next
    Else
        SetBorder r.Borders, stl, clr, wgt
    End If
End Sub

Sub SetBorder(b, Optional stl = 1, Optional clr = 0, Optional wgt = 2)
    b.LineStyle = stl
    b.Color = clr
    b.Weight = wgt
End Sub

'--------------------------------------------------------------------

SetRangeBorders [d2:k10]
SetRangeBorders [d2:k10], False, vbRed
SetRangeBorders [d2:k10], , , xlThick

Tags:

Vb Example