在 VBA 中同时设置左右单元格边框

Setting Left and Right cell borders at the same time in VBA

想知道是否有一种方法可以用一条语句设置单元格的左右边框?类似于 msgBox 配置可以 combined/added 在一起的方式(例如 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

不确定我是否会称之为更优雅的方式,但这是不重复代码的选项

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循环。

这里有一个稍微有点老套的方法来实现 one-liner,其中 rng 是我们已经定义的 Range 对象:

rng.Offset(0, -1).Resize(1, 3).Borders(xlInsideVertical).LineStyle = xlContinuous

诀窍是您希望将包含 left-hand 和 right-hand 单元格的范围设为目标范围,然后为该组单元格设置内部垂直边框。这具有设置原始单元格的 left-hand 和 right-hand 边框的效果。

  • Offset(0, -1)转到目标单元格的left-hand单元格
  • 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 列中的单元格。或者,就此而言,它不适用于 [=43= 的 right-hand 最列].这些 'edge' 个案例需要额外的编码。

正如他们所说,给猫剥皮的方法很多..怎么样:

Dim edge As Variant

For edge = xlEdgeLeft To xlEdgeRight Step xlEdgeRight - xlEdgeLeft
    Cells(j, i).Borders(edge).LineStyle = xlContinuous
Next