替换边框颜色而不影响边框的重量

问题描述 投票:0回答:1

我不是一个编码器,但我试图在不影响Excel中边框的重量的情况下替换边框颜色,但遗憾的是我编写的代码没有。请求你们帮我解决代码中的错误。

Sub BorderReplace()
Dim Top, Bottom, Left, Right
Cells.Select

'Save Border Weights
Top = Selection.Borders(x1EdgeTop).Weight
Bottom = Selection.Borders(x1EdgeBottom).Weight
Left = Selection.Borders(x1EdgeLeft).Weight
Right = Selection.Borders(x1EdgeRight).Weight

'Select Border Color
Selection.Borders.Color = RGB(150, 150, 150)

'Reapply Border Weights
Selection.Borders(x1EdgeTop).Weight = Top
Selection.Borders(x1EdgeBottom).Weight = Bottom
Selection.Borders(x1EdgeLeft).Weight = Left
Selection.Borders(x1EdgeRight).Weight = Right

End Sub

提前致谢!此外,非常感谢更好的代码或现有代码的解决方案。虽然当我尝试运行代码时,以下错误运行时错误:1004

excel vba excel-vba
1个回答
0
投票

您无需获取边框权重并重新应用它们。下面的这条线足以改变边框颜色。其他财产不会受到影响。

Selection.Cells.Borders.Color = RGB(150, 150, 150)

另外,您将Borders设置为Selection。这不是有效的操作。你可以将borders设置为Cells。所以,将Selection.Borders改为Selection.Cells.Borders

编辑:

由于您在选择中有多种边框样式(粗和细),因此将应用默认边框样式。

Sub BorderReplace()
Dim Top, Bottom, Left, Right
Dim rng As Range
Set rng = Selection

For Each cel In rng.Cells
    With cel
        Top = .Borders(xlEdgeTop).Weight
        Bottom = .Borders(xlEdgeBottom).Weight
        Left = .Borders(xlEdgeLeft).Weight
        Right = .Borders(xlEdgeRight).Weight

        .Borders(xlEdgeTop).Weight = Top
        .Borders(xlEdgeTop).color = RGB(150, 150, 150)
        .Borders(xlEdgeBottom).Weight = Bottom
        .Borders(xlEdgeBottom).color = RGB(150, 150, 150)
        .Borders(xlEdgeLeft).Weight = Left
        .Borders(xlEdgeLeft).color = RGB(150, 150, 150)
        .Borders(xlEdgeRight).Weight = Right
        .Borders(xlEdgeRight).color = RGB(150, 150, 150)
    End With
Next
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.