In Excel, drawing borders on cells is a common task to make data easier to read. While you can do this manually with a mouse, using VBA is very effective for large ranges or repetitive tasks.
In this article, I will introduce two patterns for drawing borders using VBA:
- Drawing borders on all gridlines within a cell range.
- Drawing borders only on the outer frame of a cell range.
Sample Code
Sub ApplyBordersToCells()
' Method 1: Draw borders on all gridlines in the range
Range("C3:E5").Borders.LineStyle = xlContinuous
' Method 2: Draw borders only on the outer edge of the range
Range("C8:E10").BorderAround Weight:=xlMedium
End Sub
Explanation of the Code
Method 1: Draw Borders on All Boundaries
Range("C3:E5").Borders.LineStyle = xlContinuous
This applies a standard solid line (xlContinuous) to all boundaries (top, bottom, left, and right) of the specified cell range (e.g., C3 to E5).
You can also specify other styles for LineStyle, such as xlDash (dashed line) or xlDot (dotted line).
Method 2: Draw Borders Only on the Outer Frame
Range("C8:E10").BorderAround Weight:=xlMedium
This sets a border only on the outer edge of the specified cell range.
Using Weight:=xlMedium draws a slightly thicker line. You can also use xlThin (thin line) or xlThick (thick line).
Use Cases
- Decoration: Separating different blocks in a summary table.
- Emphasis: Clearly indicating input fields.
- Layout: Formatting sheets to make them look good when printed.
Important Notes
- Using
.Bordersapplies the style to all gridlines (both inside and outside). - If you only want an outer frame, it is more appropriate to use
.BorderAround. - If you need to apply different styles to specific sides, you can specify them individually, such as
Borders(xlEdgeTop).
Summary
In this article, I introduced two ways to draw cell borders using Excel VBA.
| Method | Feature |
| .Borders.LineStyle | Applies borders to all cell boundaries within the range. |
| .BorderAround | Applies borders only to the outer frame of the range. |
Automating borders with VBA not only streamlines table formatting but also helps maintain visual consistency across your documents.
