Excel noob here (sorry). My macro runs like this:
Dim CellA, CellB As Range
Range("A1") = 25
Set CellA = Range("A1")
Range("A1") = 50
Set CellB = Range("A1")
The problem is after this, CellA
also will be equal to 50
.
Is it possible to adjust the code to keep CellA
as 25
but still use A1 as the source?
No, it's clearly not possible, I'll try to explain you why. In this piece of code, you are saying:
Dim CellA As Range '<-- CellA will be an object of type "Range"
Set CellA = Range("A1") '<-- CellA will point to the Range("A1")
This means that, no matter what, CellA
will always be pointing to Range("A1")
. So, when you change:
Range("A1") = 50 '<-- please note: when you write this, you're "implicitely" writing Range("A1").Value = 50. The ".Value" is in fact the default property of the range object (if you don't specify anything, you will set that one).
... the value of CellA
will be the value of Range("A1")
, which is exactly what you told it to be when saying Set CellA = Range("A1")
.
If you want to store the value (and not the Range object, as you're doing now), and not the whole range object, then you should do this:
Dim CellA As Long
CellA = Range("A1").Value
Even if the value of Range("A1")
will change later in run-time, the value of CellA
will still be the old one.
And this is surely what you want to do, because you don't care about the whole range object but only about its value: do you?