excel - 何时使用 range.value?

标签 excel vba

如果我正在读取/写入范围,什么时候只使用范围名称以及什么时候需要使用 range.value?范围是一个单元格还是多个单元格有关系吗?变量的类型重要吗?或者范围内数据的类型?

例如,我应该写 a = Range("Test") 还是应该写 a = Range("Test").value

同样,Range("Test") = aRange("Test").value = a

最佳答案

在 Excel Range 对象中,默认的 memberValue

所以 SomeVariable = Range("A1")SomeVariable = Range("A1").Value

同样,Range("A1") = SomeVariableRange("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").ValueMyar = 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/

相关文章:

excel - 如何在同一 if 语句中回收长公式

excel - 间接和 Vlookup 引用错误

Excel VBA 代码适用于我,但不适用于其他人

vba - 通过 VBA 插入数组公式

删除工作表后Excel Vba停止执行

java - 是否有用于解析 Excel 2007 文件的 Java 开源库?

excel - SUMIF 函数与另一个单元格中的条件

vba - Excel VBA 检查工作簿是否打开,如果没有打开

VBA Excel 将副本另存为 txt 文件

excel - 将工作簿中的每个工作表保存为单独的 CSV 文件