#001 Sub AddBorders()
#002 Dim rng As Range
#003 Set rng = Range("B4:G10")
#004 With rng.Borders
#005 .LineStyle = xlContinuous
#006 .Weight = xlThin
#007 .ColorIndex = 5
#008 End With
#009 rng.BorderAround xlContinuous, xlMedium, 5
#010 Set rng = Nothing
#011 End Sub
代码解析:
AddBorders过程为单元格区域B4:G10设置内部统一边框并添加一个加粗外边框。
第4行到第8行代码使用Borders属性引用单元格区域的Borders集合,其中第5行代码设置其边框样式线条的样式,第6行代码设置边框线条的粗细,第7行代码设置边框的颜色。
应用于Range对象的Borders集合代表Range对象的4个边框(左边框、右边框、顶部边框和底部边框)的4个Border对象组成的集合,这4个边框既可单独返回,也可作为一个组同时返回。
第9行代码使用BorderAround方法为单元格区域添加一个加粗外边框。
应用于Range对象的BorderAround方法向单元格区域添加整个区域的外边框,并设置该边框的相关属性,其语法如下:
BorderAround(LineStyle, Weight, ColorIndex, Color)
其中LineStyle参数设置边框线条的样式,Weight参数设置边框线条的粗细,ColorIndex 设置边框颜色,Color参数以RGB值指定边框的颜色。
注意 指定Color参数可以设置颜色为当前调色板之处的其它颜色,不能同时指定ColorIndex参数和Color参数。
运行AddBorders过程,效果如图 114所示。

图 114 设置单元格区域边框
如果需要在单元格区域中应用多种边框格式,则需分别设置各边框格式,如下面的代码所示。
#001 Sub BordersDemo()
#002 Dim rng As Range
#003 Set rng = Sheet2.Range("B4:G10")
#004 With rng.Borders(xlInsideHorizontal)
#005 .LineStyle = xlDot
#006 .Weight = xlThin
#007 .ColorIndex = 5
#008 End With
#009 With rng.Borders(xlInsideVertical)
#010 .LineStyle = xlContinuous
#011 .Weight = xlThin
#012 .ColorIndex = 5
#013 End With
#014 rng.BorderAround xlContinuous, xlMedium, 5
#015 Set rng = Nothing
#016 End Sub
代码解析:
BordersDemo过程代码为单元格区域内部边框在水平和垂直方向上应用不同格式,并为区域添加一个加粗外边框。
Borders(index)属性返回单个Border对象,其Index参数取值可为表格 112所列的XlBordersIndex常量之一:
常量 | 值 | 描述 |
xlDiagonalDown | 5 | 斜下边框 |
xlDiagonalUp | 6 | 斜上边框 |
xlEdgeBottom | 9 | 底部边框 |
xlEdgeLeft | 7 | 左边框 |
xlEdgeRight | 10 | 右边框 |
xlEdgeTop | 8 | 顶部边框 |
xlInsideHorizontal | 12 | 内部水平 |
xlInsideVertical | 11 | 内部垂直 |
表格 112 XlBordersIndex常量
运行BordersDemo过程效果如图 11所示。

图 115 应用不同格式内部边框
1-4 灵活设置单元格的行高列宽
一般情况下单元格的行高列宽都是以磅为单位进行设置的,也可以使用英寸和厘米计量单位设置单元格的行高列宽,如下面的代码 所示。
#001 Sub RngToPoints()
#002 With Range("A1")
#003 .RowHeight = Application.CentimetersToPoints(2)
#004 .ColumnWidth = Application.CentimetersToPoints(1.5)
#005 End With
#006 With Range("A2")
#007 .RowHeight = Application.InchesToPoints(1.2)
#008 .ColumnWidth = Application.InchesToPoints(0.3)
#009 End With
#010 End Sub
代码解析:
RngToPoints过程以英寸和厘米计量单位设置单元格的行高列宽。
第3、4行代码使用CentimetersToPoints方法以厘米为计量单位设置A1单元格的行高列宽。CentimetersToPoints方法将计量单位从厘米转换为磅(一磅等于 0.035 厘米),语法如下: