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

时间:2017-12-28 06:53:54

标签: excel vba excel-vba

我不是一个编码器,但我试图在不影响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

1 个答案:

答案 0 :(得分: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