Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

excel

border

vba

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
like image 755
Tribias Avatar asked Nov 06 '16 16:11

Tribias


2 Answers

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
like image 169
Karpak Avatar answered Sep 28 '22 18:09

Karpak


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
like image 45
Niclas Avatar answered Sep 28 '22 19:09

Niclas