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

这是将在单元格A1周围创建边框的代码:

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':类型不匹配”。)

任何人都对缩短上述内容有任何想法,还是我将不得不忍受?

最佳答案

边界名称是常量,只需定义不带撇号的数组即可。
您可以将整个borders集合称为一个,而不指定任何边界,因此只需使用with Selection.borders...https://msdn.microsoft.com/en-us/library/office/ff837809.aspx


(这两个建议独立工作)

08-16 14:38