如何在基础单元格更改后维护 excel vba 中的范围定义?
How to maintain a range definition in excel vba after underlying cell changes?
Excel 菜鸟在这里(抱歉)。我的宏是这样运行的:
Dim CellA, CellB As Range
Range("A1") = 25
Set CellA = Range("A1")
Range("A1") = 50
Set CellB = Range("A1")
问题是在这之后,CellA
也会等于50
。
是否可以调整代码以保持 CellA
为 25
但仍然使用 A1 作为来源?
不,这显然不可能,我会尽力向您解释原因。
在这段代码中,您说的是:
Dim CellA As Range '<-- CellA will be an object of type "Range"
Set CellA = Range("A1") '<-- CellA will point to the Range("A1")
这意味着,无论如何,CellA
将始终指向 Range("A1")
。所以,当你改变时:
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).
... CellA
的值将是 Range("A1")
的值,这 正是 你说 [=] 时告诉它的值17=].
如果您想存储 值(而不是像您现在所做的那样存储 Range 对象),而不是整个范围对象,那么您应该这样做:
Dim CellA As Long
CellA = Range("A1").Value
即使 Range("A1")
的值在 运行 以后发生变化,CellA
的值仍然是旧值。
这肯定是您想要做的,因为您不关心整个范围对象,只关心它的值:是吗?
Excel 菜鸟在这里(抱歉)。我的宏是这样运行的:
Dim CellA, CellB As Range
Range("A1") = 25
Set CellA = Range("A1")
Range("A1") = 50
Set CellB = Range("A1")
问题是在这之后,CellA
也会等于50
。
是否可以调整代码以保持 CellA
为 25
但仍然使用 A1 作为来源?
不,这显然不可能,我会尽力向您解释原因。 在这段代码中,您说的是:
Dim CellA As Range '<-- CellA will be an object of type "Range"
Set CellA = Range("A1") '<-- CellA will point to the Range("A1")
这意味着,无论如何,CellA
将始终指向 Range("A1")
。所以,当你改变时:
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).
... CellA
的值将是 Range("A1")
的值,这 正是 你说 [=] 时告诉它的值17=].
如果您想存储 值(而不是像您现在所做的那样存储 Range 对象),而不是整个范围对象,那么您应该这样做:
Dim CellA As Long
CellA = Range("A1").Value
即使 Range("A1")
的值在 运行 以后发生变化,CellA
的值仍然是旧值。
这肯定是您想要做的,因为您不关心整个范围对象,只关心它的值:是吗?