Vba 仅应用条件格式 top/bottom 边框?

Vba apply conditional formatting top/bottom border only?

我正在使用以下 vba 代码来应用条件格式。

Sub ResetConditions()
    With Worksheets(1).Range("A9:P1048576")
        .FormatConditions.Add Type:=xlExpression, Formula1:= _
          "=ROW(B9)=ROW(OFFSET($B,COUNTA($B:$B)-2,0))"
        With .FormatConditions(.FormatConditions.Count)
            .SetFirstPriority

            With .Borders
            .LineStyle = xlContinuous
            .Weight = xlThin
            .Color = vbRed
            End With

        End With
    End With
End Sub

边框显示为:

但我希望它看起来像这样:

我正在尝试仅设置 top/bottom 边框,如下所示:

Sub ResetConditions()
        With Worksheets(1).Range("A9:P1048576")
            .FormatConditions.Add Type:=xlExpression, Formula1:= _
              "=ROW(B9)=ROW(OFFSET($B,COUNTA($B:$B)-2,0))"
            With .FormatConditions(.FormatConditions.Count)
                .SetFirstPriority

                With .Borders(xlEdgeTop)
                .LineStyle = xlContinuous
                .Weight = xlThin
                .Color = vbRed
                End With

            End With
        End With
    End Sub

但我一直收到无法设置边框 class 的线型 属性 的错误。

谁能告诉我哪里出错了?

这是我用于边界范围的内容:

Public Sub BorderMe(my_range)

    Dim l_counter   As Long

    For l_counter = 7 To 10 '7 to 10 are the magic numbers for xlEdgeLeft etc
        With my_range.Borders(l_counter)
            .LineStyle = xlContinuous
            .Weight = xlMedium
        End With
    Next l_counter

End Sub

您可以编辑颜色、重量、样式等。 7、8、9、10是xlEdgeLeftxlEdgeRightxlEdgeTopxlEdgeBottom

的Excel数的魔术师

运行它是这样的:call borderme(selection)在立即window,看看是做什么的。

   Rng.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _
    Formula1:="=10"
Rng.FormatConditions(Rng.FormatConditions.Count).SetFirstPriority
With Rng.FormatConditions(Rng.FormatConditions.Count).Borders(xlTop)
    .LineStyle = xlContinuous
    .TintAndShade = 0
    .Weight = xlThin
    .Color = vbRed
End With
With Rng.FormatConditions(Rng.FormatConditions.Count).Borders(xlBottom)
    .LineStyle = xlContinuous
    .TintAndShade = 0
    .Weight = xlThin
    .Color = vbRed
End With

试试这个代码不要忘记设置 rng Set Rng = Range("")

像这样尝试...

Sub ResetConditions()
    Dim ws As Worksheet
    Dim Rng As Range
    Dim n As Integer
    Set ws = Sheets(1)
    Set Rng = ws.Range("A9:P1048576")

    Rng.FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=ROW(B9)=ROW(OFFSET($B,COUNTA($B:$B)-2,0))"
    n = Rng.FormatConditions.Count
    Rng.FormatConditions(n).SetFirstPriority
    With Rng.FormatConditions(n).Borders(xlTop)
        .LineStyle = xlContinuous
        .Weight = xlThin
        .Color = vbRed
    End With
    With Rng.FormatConditions(n).Borders(xlBottom)
        .LineStyle = xlContinuous
        .Weight = xlThin
        .Color = vbRed
    End With
End Sub