vba border code example
Example 1: excel vba set range borders like grid
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: vba cell all borders
ActiveSheet.Range("A1:C3").Borders.LineStyle = xlContinuous
Example 3: vba default border
Sub SelectedCellsBordersForceDefault()
Dim sFunct As String: sFunct = "SelectedCellsBordersForceDefault"
Dim bDebugging As Boolean: bDebugging = True
If (bDebugging = True) Then
Debug.Print Format(DateTime.Now, "hh:mm:ss") & " INFO " & sFunct & "| " _
& "Running.. [Cells to edit borders:" & Selection.Address & "]"
End If
Dim wbInit As Workbook: Set wbInit = ActiveWorkbook
Dim wsInit As Worksheet: Set wsInit = ActiveSheet
Dim s_rInit As String: s_rInit = Selection.Address
Dim sErrMsg As String
Dim rFocus As Range
Dim iLineStyle As Long
Dim iThemeColor As Long
Dim dTintAndShade As Double
Dim iWeight As Long
Dim iNormalBorder(1) As Integer
Dim iGreyBorder(5) As Integer
On Error GoTo ErrHandling
Application.ScreenUpdating = False
Set rFocus = Selection
iLineStyle = xlContinuous
iThemeColor = 3
dTintAndShade = -0.099978637
iWeight = xlThin
iNormalBorder(0) = xlDiagonalDown
iNormalBorder(1) = xlDiagonalUp
iGreyBorder(0) = xlEdgeLeft
iGreyBorder(1) = xlEdgeTop
iGreyBorder(2) = xlEdgeBottom
iGreyBorder(3) = xlEdgeRight
iGreyBorder(4) = xlInsideVertical
iGreyBorder(5) = xlInsideHorizontal
With rFocus
For Each edge In iNormalBorder
.Borders(edge).LineStyle = xlNone
Next
For Each edge In iGreyBorder
With .Borders(edge)
.LineStyle = iLineStyle
.ThemeColor = iThemeColor
.TintAndShade = dTintAndShade
.Weight = iWeight
End With
Next
End With
wbInit.Activate
wsInit.Activate
Range(s_rInit).Select
If (bDebugging = True) Then
Debug.Print Format(DateTime.Now, "hh:mm:ss") & " INFO " & sFunct & "| " _
& "Complete [if not debugging, make bDebugging = false]"
End If
Application.ScreenUpdating = True
Exit Sub
ErrHandling:
Application.ScreenUpdating = True
Debug.Print Format(DateTime.Now, "hh:mm:ss") & " INFO " & sFunct & "| " _
& " -> Failed"
MsgBox _
Title:="Errors in the function: " & sFunct _
, Prompt:=Err.Description _
& vbNewLine & sErrMsg _
, Buttons:=vbCritical
End Sub