如果包含链接到其他工作表的公式的单元格范围输出不同的值,如何触发macros

我正在运行以下macros以在一系列单元格上应用条件格式。 我想要的是macros随着时间的变化而被触发。 单元格值不会被手动更改(即不会由用户select并更改),它们会自动更改,因为它们包含链接到其他电子表格单元格的公式。

这样做最有效率是什么?

Sub TestSub3() Dim i As Integer, j As Integer For i = 5 To 27 If i Mod 2 <> 0 Then For j = 2 To 16 If Cells(i, j) = 0 Then Cells(i, j).Interior.Color = RGB(146, 208, 80) 'light green fill Cells(i, j).Font.Color = RGB(0, 176, 80) 'dark green font ElseIf Cells(2, 1) - Cells(i, 1) > 60 And Cells(i, j) > 0 Then Cells(i, j).Interior.Color = RGB(255, 0, 0) 'red fill Cells(i, j).Font.Color = RGB(255, 255, 0) 'yellow font ElseIf Cells(2, 1) - Cells(i, 1) > 52 And Cells(i, j) > 0 Then Cells(i, j).Interior.Color = RGB(255, 192, 0) 'orange fill, black font ElseIf Cells(2, 1) - Cells(i, 1) > 45 And Cells(i, j) > 0 Then Cells(i, j).Interior.Color = RGB(255, 255, 0) 'yellow fill, black font End If Next j End If Next i End Sub 

您可以使用“Private Sub Workbook_SheetCalculate(ByVal Sh As Object)”子例程来执行更改function。 将下面的代码粘贴到Microsoft excel对象 – > sheetname的地方。 也看看附图

Private Sub Workbook_SheetCalculate(ByVal Sh As Object)

  Dim i As Integer, j As Integer For i = 5 To 27 If i Mod 2 <> 0 Then For j = 2 To 16 'Debug.Print Cells(i, j) If Cells(i, j).Value = 0 Then Cells(i, j).Interior.Color = RGB(146, 208, 80) 'light green fill Cells(i, j).Font.Color = RGB(0, 176, 80) 'dark green font ElseIf (Cells(2, 1).Value - Cells(i, 1).Value) > 60 And Cells(i, j).Value > 0 Then Cells(i, j).Interior.Color = RGB(255, 0, 0) 'red fill Cells(i, j).Font.Color = RGB(255, 255, 0) 'yellow font ElseIf (Cells(2, 1).Value - Cells(i, 1).Value) > 52 And Cells(i, j).Value > 0 Then Cells(i, j).Interior.Color = RGB(255, 192, 0) 'orange fill, black font ElseIf (Cells(2, 1).Value - Cells(i, 1).Value) > 45 And Cells(i, j).Value > 0 Then Cells(i, j).Interior.Color = RGB(255, 255, 0) 'yellow fill, black font End If Next j End If End Sub 

您也可以查看链接以供参考 在这里输入图像说明 https://msdn.microsoft.com/en-us/library/office/ff839775.aspx