excelvbaconditional-formatting

Vba apply conditional formatting top/bottom border only?


I am using the following vba code to apply conditional formatting.

Sub ResetConditions()
    With Worksheets(1).Range("A9:P1048576")
        .FormatConditions.Add Type:=xlExpression, Formula1:= _
          "=ROW(B9)=ROW(OFFSET($B$9,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

The border is showing as this:

enter image description here

But i want it to look like this:

enter image description here

I am trying to set only top/bottom borders like so:

Sub ResetConditions()
        With Worksheets(1).Range("A9:P1048576")
            .FormatConditions.Add Type:=xlExpression, Formula1:= _
              "=ROW(B9)=ROW(OFFSET($B$9,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

But i keep getting an error unable to set linestyle property of border class.

Please can someone show me where i am going wrong?


Solution

  • Try it like this...

    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$9,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