想知道是否有办法用单个语句设置单元格的左右边框?类似msgBox
配置可以组合/添加的方式(例如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,这是我用来回答上述问题的完整解决方案。正如我所建议的那样,我创建了一个辅助函数并将它传递给我想要设置边框的单元格和线条样式&重量我喜欢它们,将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
答案 0 :(得分:3)
不确定我是否会以更优雅的方式称呼它,但这是不重复代码的选项
Dim edges(1) As Variant
edges(0) = xlEdgeLeft
edges(1) = xlEdgeRight
For Each edge In edges
ActiveCell.Borders(edge).LineStyle = xlContinuous
Next edge
答案 1 :(得分:0)
怎么样:
With Cells(j, i)
.Borders(xlEdgeLeft).LineStyle = xlContinuous
.Borders(xlEdgeRight).LineStyle = xlContinuous
End With
使用此功能,您不需要额外的for
循环。
答案 2 :(得分:0)
这是一种稍微晦涩的方式,可以将rng
作为我们已定义的Range
对象进行单行处理:
rng.Offset(0, -1).Resize(1, 3).Borders(xlInsideVertical).LineStyle = xlContinuous
诀窍在于,您希望获得包含左手和右手单元格到目标范围的范围,然后为该组单元格设置内部垂直边框。这具有设置原始单元格的左侧边框和右侧边框的效果。
Offset(0, -1)
转到目标单元格的左侧单元格Resize(1, 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栏中的单元格不起作用。或者,就此而言,它不会在工作表的最右边一列中工作。这些边缘将需要额外的编码。例。
答案 3 :(得分:0)
有很多方法可以给猫皮肤涂抹,就像他们说的那样......怎么样:
Dim edge As Variant
For edge = xlEdgeLeft To xlEdgeRight Step xlEdgeRight - xlEdgeLeft
Cells(j, i).Borders(edge).LineStyle = xlContinuous
Next