总的来说,我的目标是创建一个 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 行的条件格式后停止。
为什么它只输入第一行?