Adding all borders to a selected range, is there a shorter way to write the code?

17,598

Solution 1

You can use the below statements

Dim myRange As Range
Set myRange = Range("A6:O6")

With myRange.Borders
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With

Solution 2

Try this. It will add a border around every cell in the range A6:O6.

Sub Macro1()
     Dim rng As Range
     ' Define range
     Set rng = Range("A6:O6")

     With rng.Borders
         .LineStyle = xlContinuous
         .Weight = xlThin
         .ColorIndex = 0
         .TintAndShade = 0
     End With
End Sub
Share:
17,598
Tribias
Author by

Tribias

Updated on June 27, 2022

Comments

  • Tribias
    Tribias almost 2 years

    I am adding all borders to a certain range, In my case (A6:O6),in excel VBA, the below code works but I'd imagine there would have to be a shorter way to write it. I found a single line of code that puts a border around the whole selection but not around every cell.

    Range("A6:O6").Select
        Selection.Borders(xlDiagonalDown).LineStyle = xlNone
        Selection.Borders(xlDiagonalUp).LineStyle = xlNone
        With Selection.Borders(xlEdgeLeft)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlThin
        End With
        With Selection.Borders(xlEdgeTop)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlThin
        End With
        With Selection.Borders(xlEdgeBottom)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlThin
        End With
        With Selection.Borders(xlEdgeRight)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlThin
        End With
        With Selection.Borders(xlInsideVertical)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlThin
        End With
        With Selection.Borders(xlInsideHorizontal)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlThin
        End With