我在Excel中有一个模块,我需要在工作表中更改任何单元格时自动运行。
现在看来,如果我在具有该功能的单元格上进入编辑模式然后按回车键或者如果我点击Ctrl+Alt+F9
,它就会运行。
我怎么能做到这一点?另外,我对VB或Excel宏和模块也不太了解,也没有写这段代码。
这是我模块中的代码......
Function ColorFunction(rColor As Range, rRange As Range, Optional SUM As Boolean)
Dim rCell As Range
Dim lCol As Long
Dim vResult
lCol = rColor.Interior.ColorIndex
If SUM = True Then
For Each rCell In rRange
If rCell.Interior.ColorIndex = lCol Then
vResult = WorksheetFunction.SUM(rCell, vResult)
End If
Next rCell
Else
For Each rCell In rRange
If rCell.Interior.ColorIndex = lCol Then
vResult = 1 + vResult
End If
Next rCell
End If
ColorFunction = vResult
End Function
答案 0 :(得分:1)
我只是将Application.Volatile
放在你的宏的开头,这似乎在我测试它时按预期工作,但请注意Andy G的上述纪念:
...更改颜色不会导致重新计算,也不会触发更改事件...更改单元格值对公式结果没有影响
如果您确实希望颜色更改触发重新计算,我们需要采用不同的方法。
Function ColorFunction(rColor As Range, rRange As Range, Optional SUM As Boolean)
Dim rCell As Range
Dim lCol As Long
Dim vResult
Application.Volatile
lCol = rColor.Interior.ColorIndex
If SUM = True Then
For Each rCell In rRange
If rCell.Interior.ColorIndex = lCol Then
vResult = WorksheetFunction.SUM(rCell, vResult)
End If
Next rCell
Else
For Each rCell In rRange
If rCell.Interior.ColorIndex = lCol Then
vResult = 1 + vResult
End If
Next rCell
End If
ColorFunction = vResult
End Function