excel cell value with border code example

Example 1: excel vba highlight cells using the hex color value within the cells

'VBA function to color cells in selected range based on the hex
'color number entered in each cell. For example, #FF69B4

Sub ColorCellsByHex()
    Dim r
    If TypeName(Selection) <> "Range" Then Exit Sub
    For Each r In Selection
        r.Interior.Color = Abs(("&H" & Mid(r, 6, 2) & Mid(r, 4, 2) & Mid(r, 2, 2)))
    Next
End Sub

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