如何为单元格应用边框?
要在 Excel 中使用 VBA 将边框应用到单元格,可以使用两种不同的方法。第一个是“Borders”属性,第二个是“BorderAround”方法。这两种方法之间的唯一区别在于“边框”属性,您甚至可以将边框应用于单元格的一侧,并将其周围的边框完全应用于单元格。
在本教程中,我们将探索这两种方法,并了解添加边框的不同方法。
VBA 边框属性
- 首先,您需要使用范围对象指定要应用边框的范围或单元格。

- 之后,键入句点 (.),然后从属性和方法列表中选择“Borders”属性。

- 然后从可用内容中指定边界索引。这里我使用“xlEdgeBottom”将边框仅应用到单元格的底部。

- 从那里,使用“LineStyle”指定线条样式。我使用“xlContinuonus”作为线条样式。

Sub vba_borders() Range("A1") _ .Borders(xlEdgeBottom) _ .LineStyle = XlLineStyle.xlContinuous End Sub现在,当您运行此代码时,它将在单元格 A1 的底部添加边框。

通过颜色索引/颜色使用不同的颜色
就像您通常手动选择边框颜色一样。在 border 属性中,您还可以使用颜色索引和 color 属性来使用默认颜色以外的颜色。
考虑下面的代码。
With Range("A1").Borders(xlEdgeBottom) .LineStyle = XlLineStyle.xlContinuous .Color = RGB(255, 0, 0) End With当您运行此宏时,它会在单元格底部添加一个红色边框。

或者如果你想使用 colorindex 属性,代码将是这样的。
With Range("A1").Borders(xlEdgeBottom) .LineStyle = XlLineStyle.xlContinuous .ColorIndex = 7 End With
相关:带声明的 VBA
在单元格内添加边框
如果要在单元格内应用边框,在这种情况下,您需要使用“xlDiagonalUp”和“xlDiagonalDown”作为xlBorderIndex。
With Range("A1").Borders(xlDiagonalUp) .LineStyle = XlLineStyle.xlDashDotDot .Color = RGB(255, 0, 0) End With With Range("A1").Borders(xlDiagonalDown) .LineStyle = XlLineStyle.xlDashDotDot .Color = RGB(255, 0, 0) End With
当您运行上面的代码时,它会在单元格内添加上下边框。
VBA 边框方法
在 VBA 的 BorderAround 属性中,有 5 个可选参数,但必须指定两个参数才能正确地将边框应用到单元格。

运行宏时,以下代码将应用范围 A1:A3 周围的边框。
Range("A1:A3").BorderAround _ LineStyle:=xlContinuous, _ Weight:=xlThin
为范围内的每个单元格添加边框
以下代码循环遍历该范围内的所有单元格,并将边框一一应用于每个单元格。
Sub vba_borders() Dim iRange As Range Dim iCells As Range Set iRange = Range("A1:A10") For Each iCells In iRange iCells.BorderAround _ LineStyle:=xlContinuous, _ Weight:=xlThin Next iCells End Sub
将边框应用于所有带有文本的单元格
以下代码使用 FOR LOOP、USED RANGE、IFEMPTY 和 IF STATEMENT 仅将边框应用于具有值的单元格。
Dim iRange As Range Dim iCells As Range Set iRange = ThisWorkbook.ActiveSheet.UsedRange For Each iCells In iRange If Not IsEmpty(iCells) Then iCells.BorderAround _ LineStyle:=xlContinuous, _ Weight:=xlThin End If Next iCells删除边框
只需使用“xlNone”线条样式即可。
Range("A1").Borders(xlDiagonalDown).LineStyle = xlNone如果您想要删除工作表中包含值的所有单元格的边框,请考虑以下代码。
Dim iRange As Range Dim iCells As Range Set iRange = ThisWorkbook.ActiveSheet.UsedRange For Each iCells In iRange If Not IsEmpty(iCells) Then iCells.Borders(xlDiagonalDown).LineStyle = xlNone End If Next iCells 什么是VBA
相关教程
- 在 Excel 中使用 VBA 插入行
- 使用 VBA 代码合并 Excel 中的单元格
- 在 Excel 中使用 VBA 选择范围/单元格
- 使用 VBA 选择工作表中的所有单元格
- Excel 中 VBA 中的 ActiveCell