基本上,用Range("B" & rowPtr).EntireRow.Insert代码替换代码来添加边框!
您的代码重构,加上其他几个 tweeks
Sub BorderRows()
Dim ws As Worksheet
Dim lastRow As Long
Dim rowPtr As Long
Dim columnsToBorder As Long
Set ws = ActiveSheet
columnsToBorder = 28
With ws
lastRow = .Range("B" & .Rows.Count).End(xlUp).Row
'Optional, clear existing borders
With .UsedRange.Resize(, columnsToBorder)
.Borders(xlEdgeTop).LineStyle = xlNone
.Borders(xlEdgeBottom).LineStyle = xlNone
.Borders(xlInsideHorizontal).LineStyle = xlNone
End With
For rowPtr = 2 To lastRow
If Not IsEmpty(.Cells(rowPtr, 2)) Then
If .Cells(rowPtr, 2).Value <> .Cells(rowPtr - 1, 2).Value Then
With .Cells(rowPtr, 1).Resize(1, columnsToBorder).Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThick
End With
End If
End If
Next
'Optional, add borber to last row
With .Cells(lastRow, 1).Resize(1, columnsToBorder).Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThick
End With
End With
End Sub