如何确定Excel中SheetChange事件的新的和以前的单元格值?

我的Excel工作簿中有一些特殊的单元格,由我的Excel加载项pipe理。 我想阻止用户改变这些单元格的内容,但我也想知道,用户想要input到这些单元格的价值。 在SheetChange事件上,我可以查看哪些用户input了我的特殊单元格,但是如何确定这些单元格中的PREVIOUS值以及REVERT用户更改?


这不是我的解决scheme。 如果我在Excel中locking单元格,它变成只读 – 用户甚至不能尝试input任何东西到这个单元格 – 在这种情况下Excelpopup警告对话框。 我的问题是,我想捕捉用户input到我的单元格,用这个值做一些事情,然后将单元格内容恢复到原始值。

如何这样的,这是在VBA,但应该是相当容易翻译成C#

Option Explicit ' We are monitoring cell B2... Private initialB2Value As Variant ' holds the value for reinstatement when the user changes it Private Sub Worksheet_Activate() ' record the value before the user makes any changes. ' Could be a constant value, or you could use .Formula to ensure a calculation is not lost initialB2Value = Range("B2").Value End Sub Private Sub Worksheet_Change(ByVal Target As Range) Static alreadyChanging As Boolean ' when we reset the cell, Worksheet_Change will fire again, so we'll use a flag ' to tell us if we should care or not... If alreadyChanging Then ' change is because of this code, no need to process alreadyChanging = False Exit Sub End If If IsEmpty(Intersect(Target, Range("B2"))) Then ' If the change is not happening to the range we are monitoring, ignore it Exit Sub End If ' Do something with the user's input here Debug.Print "User input " & Range("B2").Value & " into B2" ' before we reset the value, flag that we are changing the value in code alreadyChanging = True ' now apply the old value Range("B2").Value = initialB2Value End Sub 

也许它适合捕获进入单元格的价值:

 Option Explicit Dim LastText As String Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, _ ByVal Target As Excel.Range) LastText = Target.Value End Sub Private Sub Workbook_SheetChange(ByVal Sh As Object, _ ByVal Source As Range) Debug.Print LastText; Source End Sub 

如果您需要防止用户更改值,为什么不locking单元格(右键单击,格式单元格,locking),然后保护工作表(工具保护保护工作表)。 当单元格正在被编程改变时,改变locking属性并在计算之后将其改回

我会保留一个隐藏的单元格的副本。

然后,当用户更改单元格时,很容易在隐藏的工作表上find匹配的单元格。

我解决了这个使用Application.Undo检查,如果更改无效。