使用用户设计的功能进行条件格式化

时间:2012-12-04 00:07:10

标签: excel vba excel-vba user-defined-functions conditional-formatting

总的来说,我的目标是创建一个VBA宏,它将通过工作表并使用用户设计的函数应用条件格式公式。工作表分为各个组,每组31行,因此我需要基于31步骤并设置条件格式。我创建了一个名为IdentifyFormulaCells的自定义函数,该条件在条件格式中用于执行任何颜色,文本等操作。

Function IdentifyFormulaCells(rng As Range) As Boolean
'   Determine if cell contains a formula based on input range and returns True if there is a formula

IdentifyFormulaCells = rng.HasFormula

End Function

Sub LoopGroup()

    Dim rng As Range
    Dim iRng As Range
    Dim iStep As Long
    Dim ProjectRow As Long
    Dim FormulaString As String

    Dim rngStart As Range
    Dim rngEnd As Range
    Dim iCol As Long
    Dim iRow As Long
    Dim nCol As Long
    Dim nRow As Long

    Set rng = Range("I34:FH994")

    nCol = rng.Columns.Count
    nRow = rng.Rows.Count

'Sets the first project row
    ProjectRow = 34
    FormulaString = "=IdentifyFormulaCells(I" & CStr(ProjectRow) & ")"

'Based on number of employees listed per project
    iStep = 31

    For iRow = 1 To nRow Step iStep
        MsgBox "Project Row before action = " & ProjectRow
        MsgBox "FormulaString before action = " & FormulaString

        Set iRng = Range(rng.Cells(iRow, 1), rng.Cells(iRow, nCol))
        iRng.Select

        With Selection
            .FormatConditions.Delete

'THIS IS WHERE THE PROBLEM IS, NEED TO MAKE A FUNCTION OR STRING THAT INCREMENTS BASED ON THE PROJECT ROW BUT IT STOP AFTER THE FIRST GROUP

            '.FormatConditions.Add Type:=xlExpression, Formula1:="=IdentifyFormulaCells(I34)"

            .FormatConditions.Add Type:=xlExpression, Formula1:=FormulaString

        End With

        MsgBox "project row before step= " & ProjectRow
        ProjectRow = ProjectRow + iStep
        FormulaString = "=IdentifyFormulaCells(I" & CStr(ProjectRow) & ")"

    Next iRow

End Sub

如果我注释掉.FormatConditions.Add....行,那么代码会在31行的每个组中循环运行,但是当代码立即生效时,它仅在第34行输入条件格式后停止。

为什么只输入第一行?

1 个答案:

答案 0 :(得分:0)

如果目标只是识别包含公式的单元格,则可能更容易:

主页>编辑>找到&选择 - 转到特殊...,公式并将选择的格式应用于所选单元格。