减less格式化单元格所需的代码行数?

我试图减less添加边框(和其他格式)到单元格所需的行数。

以下是将在单元格A1周围创build边框的代码:

Sub test2() Dim cel As Range Set cel = Range("A1") With cel.Borders(xlEdgeTop) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With cel.Borders(xlEdgeBottom) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With cel.Borders(xlEdgeRight) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With cel.Borders(xlEdgeLeft) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With End Sub 

正如你所看到的,这些With块占用一些空间。 除了保持我的代码“紧”之外没有其他的真正原因,所以我不必滚动这么多,所以我想知道是否可以使这个更紧凑。 我想使用一个数组,但它不工作:

 Sub test() Dim arr() Dim i As Integer ReDim arr(1 To 4) Dim cel As Range Set cel = Range("A1") arr = Array("xlEdgeTop", "xlEdgeBottom", "xlEdgeRight", "xlEdgeLeft") For i = LBound(arr) To UBound(arr) With cel.Borders(arr(i)) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With Next i End Sub 

(注意:错误发生在With cel.Borders(arr(i)) ,“运行时错误13”:types不匹配“。

任何人有任何想法缩短上述,或只是我将不得不忍受的东西?

  1. 边界名称是常量,只需定义没有撇号的数组。
  2. 你可以引用整个边界集合作为一个,不要指定任何边框,所以只需使用with Selection.borders...https://msdn.microsoft.com/en-us/library/office/ff837809.aspx

(这两个build议独立工作)

如果你只是想黑色的边框(通常是默认的配色scheme),这么多的代码会做:

 With Selection.Borders() .LineStyle = xlContinuous End With 

Selection.Borders()您只需要跳过枚举。 它拖欠四方。 其余的属性,你可以根据需要进行更改。