检测多个工作表中的单元格值更改

时间:2016-10-07 08:00:22

标签: excel vba excel-vba

我试图使用Worksheet_calculate检测某个单元格值的任何变化 - 通过公式计算发生任何变化。 我最初在表单对象本身有代码,它工作正常。然后我将它添加到另一张纸上(使用相同的代码,相同的单元格范围),但无法在第二张纸中使用它。因此,我决定将代码写入单独的(ThisWorkbook)模块,以便在所有符合条件的工作表中执行它。 遇到一些问题 - 我认为目前的主要问题是我不确定如何分配之前的值“PrevVal” - 我以前使用Workbook_Open()执行此操作。

这是代码:

Private Sub Workbook_Open()
  '  PrevVal = Sheet2.Range("F2").Value
End Sub


Private Sub Workbook_SheetCalculate(ByVal Sh As Object)

  ' if sheetname begins 'Report'
  If Sh.Name Like "Report_*" Then

   ' if the monitored cell value changes (if it differs from the old pre-set value)
    If Range("F2").Value <> PrevVal Then

        ' Get the last row on the current sheet (from col AE )...
        Dim intLastRow As Long

        intLastRow = Sh.Cells(Sh.Rows.Count, "AE").End(xlUp).Row

        ' Add our value to the next row...
        Sh.Cells(intLastRow + 1, "AE") = Range("F2").Value
        Sh.Cells(intLastRow + 1, "AD") = Date
        PrevVal = Range("F2").Value
    End If       
  End If

End Sub

0 个答案:

没有答案