工作表计算-字体颜色随单元格值的变化而变化

时间:2019-01-22 10:52:12

标签: excel vba

我一直在找几个小时,但一直在寻找答案。

我有一本包含各种vlookup的工作簿。我已经将一张工作表限制为手动计算,而我正试图找到一个宏,然后该宏将手动运行计算并更改已更改单元格的字体颜色。

我目前正在使用worksheet_calculate()函数,但无法弄清楚如何使其在计算后选择单个单元格更改并更改字体颜色。

谢谢!

2 个答案:

答案 0 :(得分:1)

您需要在计算之前将所有值读入数组,以便可以将其与计算之后的值进行比较:

Option Explicit

Sub ColorChangedCellsAfterCalculation()
    Dim RangeToCheck As Range 'define which range we want to check
    Set RangeToCheck = Worksheets("Sheet1").Range("A1:C5")

    'read values BEFORE calculation into array
    Dim PreCalcValues As Variant
    PreCalcValues = RangeToCheck.Value

    'calculate
    Application.Calculate

    'read values AFTER calculation into array
    Dim PostCalcValues As Variant
    PostCalcValues = RangeToCheck.Value

    Dim ChangedData As Range 'we collect all changed cells in this variable

    'Loop through array and check which row/column values changed
    Dim iRow As Long, iCol As Long
    For iRow = 1 To RangeToCheck.Rows.Count
        For iCol = 1 To RangeToCheck.Columns.Count
            If PreCalcValues(iRow, iCol) <> PostCalcValues(iRow, iCol) Then
                If ChangedData Is Nothing Then 'collect all changed data
                    Set ChangedData = RangeToCheck(iRow, iCol) 'first changed cell
                Else
                    Set ChangedData = Union(ChangedData, RangeToCheck(iRow, iCol)) 'add all other changed cells
                End If
            End If
        Next iCol
    Next iRow

    If Not ChangedData Is Nothing Then ChangedData.Interior.Color = vbRed 'mark all changed data red
End Sub

想象一下以下数据……

enter image description here

它将变成...

enter image description here

请注意,如果对大量数据运行该比较,则将花费大量时间。因此,请勿在整个工作表上运行此操作,而仅在所需的数据范围内运行。

答案 1 :(得分:0)

您可以使用application.evaluate,评估您的公式并根据当前值检查它们:

    Sub tst()
    For Each cl In Sheet1.Cells.SpecialCells(xlCellTypeFormulas)
        If Application.Evaluate(cl.Formula) <> cl.Value Then
            cl.Interior.ColorIndex = 3
        Else
            cl.Interior.ColorIndex = xlNone
        End If
    Next cl
' application.calculate or sheet calculate
    End Sub