如果我正在读取/写入范围,什么时候只使用范围名称以及什么时候需要使用 range.value?范围是一个单元格还是多个单元格有关系吗?变量的类型重要吗?或者范围内数据的类型?
例如,我应该写 a = Range("Test")
还是应该写 a = Range("Test").value
?
同样,Range("Test") = a
或 Range("Test").value = a
?
最佳答案
在 Excel Range
对象中,默认的 member
是 Value
所以 SomeVariable = Range("A1")
与 SomeVariable = Range("A1").Value
同样,Range("A1") = SomeVariable
与 Range("A1").Value = SomeVariable
当你说a = Range("Test")时,你当然必须小心
当您尝试将连续范围内的值存储到 Variant 变量时,例如 Test
范围指的是 A1:A10
,那么您将得到一个值数组
Sub Sample()
Dim Myar
Myar = Range("A1:A10").Value
Debug.Print UBound(Myar)
End Sub
在这种情况下,Myar = Range("A1:A10").Value
与 Myar = Range("A1:A10")
If I'm reading/writing to a range, when do I just use the range name and when do I need to use range.value?
我不确定我什么时候只使用范围名称
是什么意思,但是当你使用.Value
时是否使用并不重要从某个范围读/写到某个范围。恕我直言,使用 .Value
是一个很好的做法:)
Does it matter if the range is one cell or multiple cells?
不,即使在这种情况下,是否使用 .Value
也没关系。
Does it matter what the type of the variable is?
哦,是的!请参阅上面的数组示例
Or the type of the data in the range?
Excel 单元格可以存储各种类型的数据。从数字到日期再到字符串。由于您不知道该类型是什么,因此建议在使用它们时使用 Variant
。这是一个经典的例子
假设单元格 A1
的号码为 123456789
现在试试这个代码
Sub Sample()
Dim someVariable As Integer
someVariable = Range("A1").Value
Debug.Print someVariable
End Sub
现在试试这个
Sub Sample()
Dim someVariable As Variant
someVariable = Range("A1").Value
Debug.Print someVariable
End Sub
正如蒂姆·威廉姆斯在评论中提到的
Using
.Value
is also useful to "dis-ambiguate" the common "forgot to use Set when assigning an object variable" problem -Dim a: Set a = Range("A1") vs Dim a: a = Range("A1")
In the second case always using.Value
clarifies the actual problem
关于excel - 何时使用 range.value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30538904/