Excel一键为非空单元格添加边框技巧
1、首先打开一个需要处理的Excel文档,然后将Excel文档另存为成启用宏的工作簿,后缀名为.xlsm。
2、本教程以下列数据为例。
3、先插入一个形状,作为一个启动宏代码的按钮。
4、为形状指定宏代码,在指定宏窗口选择右上角的新建。
5、此时会进入VBA界面,并弹出一个模块窗口。
6、在模块窗口覆盖粘贴以下代码:
Sub 矩形1_Click()
Dim i%, j%, m%, n%
Dim rng As Range
Set rng = Selection
Cells.Select
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
Cells(1, 1).Select
i = ActiveSheet.UsedRange.Rows.Count
j = ActiveSheet.UsedRange.Columns.Count
For m = 1 To i
For n = 1 To j
If Cells(m, n).Value <> "" Then
Cells(m, n).Select
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
Else
End If
Next
Next
End Sub
7、关闭VBA界面,回到Excel窗口,点击按钮即可实现为非空单元格添加边框。