Vba仅应用条件格式的顶部/底部边框?

时间:2017-04-19 10:01:17

标签: excel vba conditional-formatting

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

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

边框显示为:

enter image description here

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

enter image description here

我试图只设置顶部/底部边框:

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

但是我一直收到错误,无法设置border class的linestyle属性。

请有人告诉我我哪里出错了吗?

3 个答案:

答案 0 :(得分:0)

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

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),看看有什么用。

答案 1 :(得分:0)

   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设置Rng =范围("")

答案 2 :(得分:0)

尝试这样......

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