我正在嘗試減少向單元添加邊框(和其他格式)所需的行數。減少格式化單元格所需的代碼行數?
這裏是一個將創建一個邊框單元格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’」發生錯誤)
任何人對縮短上述內容有什麼想法,或者這只是我將不得不忍受的事情?
我想不出任何事情都在我頭頂。格式一直是我的許多代碼行。 – MatthewD
@cyboashu有答案,但FYI'Array(「xlEdgeTop」,「xlEdgeBottom」,「xlEdgeRight」,「xlEdgeLeft」)'應該是'Array(xlEdgeTop,xlEdgeBottom,xlEdgeRight,xlEdgeLeft)'這些是數字常量,而不是字符串。 –
@TimWilliams - 啊!這樣做:D我假設像'xlEnd'等東西也是常量,可以用同樣的方式? – BruceWayne