Overview
In Excel, adding borders to cells helps clarify the structure of a table. There are many situations where you need to apply different settings to specific parts, such as the outer frame, inner lines, top, bottom, left, or right.
In this article, I will explain how to set and retrieve detailed cell border settings using VBA. I will also explain how to hide Excel’s default gridlines to make your custom borders stand out.
Sample Code
Sub SetDetailedCellBorders()
Dim targetRange As Range
Set targetRange = Range("E3:G6")
' Set the top edge border to a medium continuous line
With targetRange.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlMedium
End With
' Set the bottom edge border to a medium continuous line
With targetRange.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlMedium
End With
' Set the inside horizontal borders to dotted lines
targetRange.Borders(xlInsideHorizontal).LineStyle = xlDot
' Hide gridlines (Improves visibility)
ActiveWindow.DisplayGridlines = False
End Sub
Code Explanation
.Borders(xlEdgeTop) / .Borders(xlEdgeBottom)
These commands set the borders for the top and bottom edges of the selected range.
- LineStyle: Set to
xlContinuous(Solid line). - Weight: Set to
xlMedium(Medium thickness).
.Borders(xlInsideHorizontal)
This applies a style to the horizontal lines inside the cell range. Here, we used xlDot (Dotted line).
To control vertical lines inside the range, use .Borders(xlInsideVertical).
ActiveWindow.DisplayGridlines = False
This hides the faint gray gridlines that appear on the Excel sheet by default. This makes the borders you drew with VBA stand out, making the table easier to read.
List of Available Border Positions (Constants)
| Constant Name | Target Area |
| xlEdgeTop | Top edge of the range |
| xlEdgeBottom | Bottom edge of the range |
| xlEdgeLeft | Left edge of the range |
| xlEdgeRight | Right edge of the range |
| xlInsideHorizontal | Horizontal lines inside the range |
| xlInsideVertical | Vertical lines inside the range |
Examples of Line Styles and Weights
LineStyle Examples:
| Constant | Description |
| xlContinuous | Solid line |
| xlDot | Dotted line |
| xlDash | Dashed line |
Weight Examples:
| Constant | Description |
| xlThin | Thin line |
| xlMedium | Medium line |
| xlThick | Thick line |
Application Examples
- Formatting tables for printing.
- Visually distinguishing between input fields and labels in a form.
- Dynamically changing border styles based on specific conditions.
Summary
In this article, I introduced how to strictly control cell borders using VBA. By using the Borders property, you can flexibly control every part of the border, including the outer frame, inner lines, and individual sides.
Using borders effectively makes Excel tables clearer and easier to read. Please use this technique when creating reports or formatting forms.
