如何为顶部合并单元格标题后每列添加整列垂直粗边框,求VBA代码
下面是适配需求的VBA代码,保留了你原有偶数行底部细边框的功能,同时新增了顶部合并标题对应列的整列垂直粗边框效果:
Sub FormatTest() Dim titleRow As Long, lastCol As Long, i As Long titleRow = 1 ' 标题所在行,如有变动可直接修改数值 With Sheets("Test") ' 原有功能:B-Z列偶数行底部添加细边框 With .Range("$B:$Z") .FormatConditions.Add xlExpression, Formula1:="=mod(row(),2)=0" With .FormatConditions(1).Borders(xlBottom) .LineStyle = xlContinuous .ColorIndex = xlAutomatic .TintAndShade = 0 .Weight = xlThin End With .FormatConditions(1).StopIfTrue = False End With ' 新增功能:合并标题对应块右侧添加整列粗垂直边框 lastCol = .Cells(titleRow, .Columns.Count).End(xlToLeft).Column For i = 2 To lastCol ' 从B列开始遍历标题行 ' 判断当前列是否为所在合并单元格的最右列 If i = .Cells(titleRow, i).MergeArea.Column + .Cells(titleRow, i).MergeArea.Columns.Count - 1 Then ' 给当前列整列添加右侧粗边框 With .Columns(i).Borders(xlEdgeRight) .LineStyle = xlContinuous .Weight = xlThick .ColorIndex = xlAutomatic End With End If Next i End With End Sub
可调整参数说明
- 若标题不在第1行,修改
titleRow = 1的数值即可 - 若不需要边框应用到整列,只需要覆盖有效数据范围,可把
.Columns(i)替换为.Range(.Cells(1, i), .Cells(.Rows.Count, i).End(xlUp)) - 若需要调整粗边框粗细,可修改
Weight = xlThick参数,可选值:xlHairline(极细)、xlThin(细)、xlMedium(中等)、xlThick(粗)
内容的提问来源于stack exchange,提问作者Raj
相关产品推荐
相关产品推荐

