跳到主要内容

使用 VBA 给单元格区域添加边框

示例一

本示例为单元格区域设置内部框线并添加一个加粗的外边框。

Sub AddBordersToRange()
    Dim rng As Range
    Set rng = Range("B2:D6") ' 要添加边框的单元格区域
    
    ' 给单元格区域添加边框
    With rng.Borders
        .LineStyle = xlContinuous ' 设置线条样式为连续线条
        .Weight = xlThin ' 设置线条粗细为细
        .Color = RGB(0, 0, 0) '设置线条颜色为黑色
    End With
    
    ' 给单元格区域添加红色加粗外边框
    rng.BorderAround LineStyle:=xlContinuous, Weight:=xlMedium, ColorIndex:=3
    
    Set rng = Nothing ' 释放变量
End Sub

代码解析

本示例代码首先使用 Range 对象的 Borders 集合快速地对单元格区域全部边框应用相同的格式,再使用 Range 对象的 BorderAround 方法单独为单元格区域添加外边框。

BorderAround 方法语法如下:

BorderAround (LineStyle, Weight, ColorIndex, Color, ThemeColor)
名称 必需/可选 数据类型 说明
LineStyle 可选 Variant XlLineStyle 的常量之一,指定边框的线条样式。
Weight 可选 XlBorderWeight 边框粗细。
ColorIndex 可选 XlColorIndex 边框颜色,作为当前调色板的索引或作为 XlColorIndex 常量。
Color 可选 Variant 边框颜色,以 RGB 值表示。
ThemeColor 可选 Variant 主题颜色,作为当前颜色主题的索引或 XlThemeColor 值。

本示例代码运行后效果如下:

设置单元格区域边框
设置单元格区域边框

示例二

如果需要在单元格区域中设置多种边框格式,则需要分别设置各个边框的格式。

Sub AddBordersDemo()
    Dim rngCell As Range
    Set rngCell = Range("B2:D6")
    
    ' 设置单元格区域水平方向边框
    With rngCell.Borders(xlInsideHorizontal)
        .LineStyle = xlDot
        .Weight = xlThin
        .Color = RGB(255, 0, 0)
    End With
    
    ' 设置单元格区域垂直方向边框
    With rngCell.Borders(xlInsideVertical)
        .LineStyle = xlContinuous
        .Weight = xlThin
        .ColorIndex = 5
    End With
    
    ' 设置单元格区域外边框
    rngCell.BorderAround xlContinuous, xlMedium, 5
    
    Set rngCell = Nothing
End Sub

代码解析

使用 Borders (index) 属性返回单个 Border 对象。 XlBordersIndex 常量列表如下所示:

常量 描述
xlDiagonalDown 5 从区域中每个单元格的左上角到右下角的边框。
xlDiagonalUp 6 从区域中每个单元格的左下角到右上角的边框。
xlEdgeBottom 9 区域底部的边框。
xlEdgeLeft 7 区域左边缘的边框。
xlEdgeRight 10 区域右边缘的边框。
xlEdgeTop 8 区域顶部的边框。
xlInsideHorizontal 12 区域中所有单元格的水平边框(区域以外的边框除外)。
xlInsideVertical 11 区域中所有单元格的垂直边框(区域以外的边框除外)。

本示例代码运行后效果如下:

单元格区域设置不同格式边框
单元格区域设置不同格式边框

示例三

如果需要清除单元格区域边框,设置 Borders 对象的 LineStyle 属性为 xlNone,需要注意的是,斜下和斜上边框需要分别设置。

Sub ClearBorders()
    With Cells
        .Borders.LineStyle = xlNone ' 清除直线边框
        .Borders(xlDiagonalDown).LineStyle = xlNone ' 清除斜下边框
        .Borders(xlDiagonalUp).LineStyle = xlNone ' 清除斜上边框
    End With
End Sub

评论

您的电子邮件地址不会显示出来。*号为必填项。