我正在尝试减少向单元格添加边框(和其他格式)所需的行数。
这里是将在单元格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':类型不匹配"。)
任何人都有任何关于缩短上述内容的想法,或者这只是我不得不忍受的事情?
答案 0 :(得分:3)
如果您只想要黑色边框(通常是默认配色方案),那么这么多代码就可以了:
With Selection.Borders()
.LineStyle = xlContinuous
End With
在Selection.Borders()
中,您只需跳过枚举即可。它违反了所有四个方面。其他属性可以根据需要进行更改。
答案 1 :(得分:1)
with Selection.borders...
(https://msdn.microsoft.com/en-us/library/office/ff837809.aspx)(两项建议独立完成)