In my Excel sheet, I have a range "plot" that triggers a sub-routine upon change. I used the following code for that:
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
This code has to first save the data from the current worksheet to a specific range, that defined by current_plot
in another worksheet (let's call it "DATA"), by calling auto_save_data (current_plot)
.
Then it restores the data from a specific range in "DATA" that is defined by Range("plot")
, by calling restore_data
.
The restore_data
sub-routine above work as expected, but auto_save_data
doesn't. The problem is that when the user change the value of "plot" I need to somehow know what was the value before the change, so I can save the data to the correct place before restoring the data from "DATA" for the value after update, and by that deleting the data in the current sheet.
I tried to use the Worksheet_SelectionChange
event, as described here:
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
But it has 2 problems:
- It didn't work. The sub-routine
Worksheet_Change
didn't seem to recognize the value of the variablecurrent_plot
, albeit, it didn't throw an error. - I tried another method from the question above, that save the old value to a hidden sheet. That worked, except when the user changes the value in "plot" without selecting another range first (then the value in the hidden sheet does not update).
So my question is: What is the simplest method (I'm very new to VBA) to use the value that was in Target
before the routine Worksheet_Change
was triggered?
EDIT: I changed "plot" to be a single cell range ($P$2), to focus the question on the real problem.