Excel宏用于格式化条件的动态范围

时间:2014-01-05 11:17:34

标签: excel vba

我之前请求帮助以获取格式化变量范围的代码,Gary's Student能够为我提供一个出色的解决方案here

我现在意识到我需要根据A列值进行格式化,并且我有点难过了,而我原来的问题并不能解决这个问题。

我现在有代码将边框应用于我的变量大小的表中的每个单元格,但我希望能够根据A列中第一个单元格的值保留没有边框的行。

例如: 如果A中的第一个单元格包含“abc”,则跳过格式化。 要么 如果A列中的第一个单元格不包含“abc”,则应用格式。

非常感谢任何帮助。

加里的学生代码:

Sub BoxIt()
Set r = Range("A1").CurrentRegion
With r.Borders(xlEdgeLeft)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With r.Borders(xlEdgeTop)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With r.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With r.Borders(xlEdgeRight)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With r.Borders(xlInsideVertical)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With r.Borders(xlInsideHorizontal)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
End Sub'

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效(此代码将新CF添加到A1范围的当前区域,并在列A 中的行不包含字符串{{}时应用格式{1}}变量):

StrToFind

一些注意事项:

1)根据您的本地设置,公式Sub test() Dim r As Range Dim StrToFind As String StrToFind = "abc" Set r = Range("A1").CurrentRegion With r .FormatConditions.Add Type:=xlExpression, Formula1:= _ "=ISERROR(FIND(""" & StrToFind & """,$A1))" .FormatConditions(.FormatConditions.Count).SetFirstPriority With .FormatConditions(1) With .Borders(xlLeft) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With .Borders(xlTop) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With .Borders(xlBottom) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With .Borders(xlRight) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With .StopIfTrue = False End With End With End Sub 可能有误,在这种情况下您应该使用"=ISERROR(FIND(""" & StrToFind & """,$A1))"(在"=ISERROR(FIND(""" & StrToFind & """;$A1))"之前查看公式中的分隔符:它是逗号或分号)。

2)每次表格改变大小时都应该调用此函数

3)表格的“正常”格式应该没有边框(仅当列$A1 中的行不包含 {{时,才会出现CF的帮助下的边框1}})

希望它有所帮助!