I've made a function in VBA for excel that counts the number of cells of a certain color in a range, based on a different cell. 开发者_Go百科This works fine first running the function, however when changing the color of one of the cells in the range to or from the color being counted, the value doesn't update. How do I get it so the function continuously updates whenever I change the color? Workbook calulations are set to automatic.
Function CountColor(rSumRange As Range)
Dim rCell As Range
Dim iCol As Integer
Dim vResult
iCol = Range("P1").Interior.ColorIndex
For Each rCell In rSumRange
If rCell.Interior.ColorIndex = iCol Then
vResult = vResult + 1
End If
Next rCell
CountColor = vResult
End Function
Changing color doesn't trigger the Worksheet_Change()
and doesn't trigger any Application.Calculate
.
If your workbook doesn't have too many formulas, you can try this bulky solution:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.Calculate
End Sub
It will come at the cost of some performance, but you can add "Application.Volatile" inside the code which will make it so that whenever there is a change in the worksheet, it's recalculated.
Ref: http://msdn.microsoft.com/en-us/library/aa213653(v=office.11).aspx
精彩评论