在VBA中同时设置左右单元格边框
想知道是否有一种方法可以用单个语句设置单元格的左右边界? 类似于msgBox
configuration的方式可以组合/添加在一起(例如vbYesNo + vbQuestion
)。 我试过了:
Cells(j, i).Borders(xlEdgeLeft + xlEdgeRight)
这导致我的错误。 单独编码每个边界有点重复…
在这里我想到了:
For i = 1 To 10 For j = 2 To 6 + numAcft Cells(j, i) = "Week Start Date" With Cells(j, i).Borders(xlEdgeLeft) .LineStyle = xlContinuous .Weight = xlMedium End With With Cells(j, i).Borders(xlEdgeRight) .LineStyle = xlContinuous .Weight = xlMedium End With ... ...
有没有更优雅的方式?
完全相信@ egan-wolf和@robinmackenzie这里是我用来回答上述问题的完整解决scheme。 如上所示,我创build了一个辅助函数,并将它传递给我想要设置边框的单元格,以及我希望它们的线条样式和重量,将8行代码变成更可读的单行:
setLeftAndRightEdges Cells(j, i), xlContinuous, xlMedium
Private Sub setLeftAndRightEdges(ByVal cell As Range, ByVal lineStyle As Long, ByVal weight As Long) Dim edges(1) As Variant Dim edge As Variant edges(0) = xlEdgeLeft edges(1) = xlEdgeRight For Each edge In edges cell.Borders(edge).LineStyle = lineStyle cell.Borders(edge).weight = weight Next edge End Sub
不知道如果我会调用它更优雅的方式,但这是不重复的代码的选项
Dim edges(1) As Variant edges(0) = xlEdgeLeft edges(1) = xlEdgeRight For Each edge In edges ActiveCell.Borders(edge).LineStyle = xlContinuous Next edge
怎么样:
With Cells(j, i) .Borders(xlEdgeLeft).LineStyle = xlContinuous .Borders(xlEdgeRight).LineStyle = xlContinuous End With
使用这个你不需要额外for
循环。
正如他们所说,有很多方法可以使猫变皮肤。
Dim edge As Variant For edge = xlEdgeLeft To xlEdgeRight Step xlEdgeRight - xlEdgeLeft Cells(j, i).Borders(edge).LineStyle = xlContinuous Next
这里有一个稍微不好的方法来做一个rng
,其中rng
是我们已经定义的Range
对象:
rng.Offset(0, -1).Resize(1, 3).Borders(xlInsideVertical).LineStyle = xlContinuous
诀窍是你想得到一个范围,包括左侧和右侧的单元格到目标范围,然后为这组单元格,设置内部垂直边框。 这具有设置原始单元的左侧和右侧边界的效果。
-
Offset(0, -1)
转到目标单元格的左侧单元格 -
Resize(1, 3)
将范围扩展到目标单元格的行上的3列 -
Borders(xlInsideVertical).LineStyle...
设置3个单元格范围的内部垂直线的格式。
示例代码:
Option Explicit Sub Test() Dim ws As Worksheet Dim rng As Range 'sheet Set ws = ThisWorkbook.Worksheets("Sheet1") 'target range Set rng = ws.Range("B8") 'one-liner to set left and right borders rng.Offset(0, -1).Resize(1, 3).Borders(xlInsideVertical).LineStyle = xlContinuous End Sub
编辑:正如@EganWolf所指出的那样,这对列A中的单元格不起作用。或者,对于这个问题,它将不会在表单的右侧列中工作。 对于这些“边缘”情况,将需要额外的编码。