当使用Worksheet_Change时 – 如何在更改之前获取单元格中的值?
在我的Excel工作表中,我有一个范围“绘图”,在更改时触发一个子程序。 我使用了以下代码:
Private Sub Worksheet_Change(ByVal Target As Range) If Target.Address = Range("plot").Address Then auto_save_data (current_plot) ' <- doesn't work restore_data End If End Sub
此代码必须首先将当前工作表中的数据保存到特定的范围,该范围由另一个工作表中的current_plot
定义(我们称之为“DATA”),方法是调用auto_save_data (current_plot)
。
然后它通过调用restore_data
来恢复由Range("plot")
定义的“DATA”中特定范围的数据。
上面的restore_data
子例程按照预期工作,但auto_save_data
不能。 问题是,当用户改变“绘图”的值时,我需要以某种方式知道改变之前的值是什么,所以我可以将数据保存到正确的位置,然后从“数据”中恢复更新后的值,并删除当前表单中的数据。
我试图使用Worksheet_SelectionChange
事件,如下所述:
Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim current_plot As Variant If Target.Address = Range("plot").Address Then current_plot = Target.Value End If End Sub
但它有两个问题:
- 它没有工作。 子例程
Worksheet_Change
似乎没有识别variablescurrent_plot
的值,尽pipe它没有引发错误。 - 我从上面的问题尝试了另一种方法,即将旧值保存到隐藏表格中。 这有效,除非用户更改“绘图”中的值而不先select另一个范围(然后隐藏工作表中的值不更新)。
所以我的问题是: 在例程Worksheet_Change
被触发之前,使用Target
的值 的最简单的方法是什么 (我对VBA很新颖) ?
编辑:我改变了“情节”是一个单细胞范围($ P $ 2),把重点放在真正的问题。
假设“Plot”是Name
为“DATA”的工作表中的单个单元格区域,请将以下代码放置在Worksheets("DATA")
的代码模块中:
'Declare a variable with global scope, ie accessible in this worksheet 'and in other code modules. Public current_plot As Variant Private Sub Worksheet_Change(ByVal Target As Range) If Target.Address = Range("plot").Address Then 'Use "current_plot" whenever the cell is changed MsgBox "Old value: " & current_plot & vbCrLf & _ "New value: " & Target.Value End If End Sub Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Target.Address = Range("plot").Address Then 'Update "current_plot" whenever the cell is selected current_plot = Target.Value End If End Sub
并将此代码放置在ThisWorkbook
代码模块中:
Private Sub Workbook_Open() 'Initialise "current_plot" when the workbook is opened Worksheets("DATA").current_plot = Worksheets("DATA").Range("Plot").Value End Sub
假设你不想知道单元格曾经是什么,但是实际上你真的想知道最后一次使用单元格的值时单元格里面是什么,可以用下面的方法简化一下:
'Declare a variable with global scope, ie accessible in this worksheet 'and in other code modules. Public current_plot As Variant Private Sub Worksheet_Change(ByVal Target As Range) If Target.Address = Range("plot").Address Then 'Use "current_plot" whenever the cell is changed MsgBox "Old value: " & current_plot & vbCrLf & _ "New value: " & Target.Value '... '... process whatever needs to be processed '... 'Save the value we used this time current_plot = Target.Value End If End Sub
并将此代码放置在ThisWorkbook
代码模块中:
Private Sub Workbook_Open() 'Initialise "current_plot" when the workbook is opened Worksheets("DATA").current_plot = Worksheets("DATA").Range("Plot").Value End Sub