如何在基本单元更改之后在excel vba中保持范围定义?
Excel noob在这里(对不起)。 我的macros像这样运行:
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")
的值,正如您在Set CellA = Range("A1")
时所说的那样。
如果你想存储的值 (而不是范围对象,如你现在所做的),而不是整个范围对象,那么你应该这样做:
Dim CellA As Long CellA = Range("A1").Value
即使Range("A1")
的值在运行时稍后会改变, CellA
的值仍旧是旧的值。
这当然是你想要做的,因为你不关心整个范围的对象,而只关心它的价值:你呢?