我知道Range()
和Cells()
属性是访问工作表上单元格的等效方法。但是,在这种组合中使用Range.Cells()
是明智的吗?
我遇到了一个他们使用Range("A1").Resize(2,3).cells.value
的例子。这是否等同于Range("A1").Resize(2,3).value
?
如果没有,前者的好处是什么?
发布于 2018-06-29 08:13:19
从技术上讲,Range
和Range.Cells
并不等同。有一个很小但很重要的区别。
但是,在您的特殊情况下,(),其中您
Range("something")
构造范围,以及.Value
感兴趣,--它对没有任何影响。
VB中有一个方便的子句For Each
,它枚举集合中的所有元素。在Excel对象模型中,有一些方便的属性,如Columns
、Rows
或Cells
,它们返回相应单元格跨的集合:列集合、行集合或单元格集合。
从语言流动的方式来看,您自然会期望For Each c In SomeRange.Columns
每次枚举一个列,而For Each r In SomeRange.Rows
则会一次枚举一个列。事实上,他们就是这样做的。
但是您可以注意到,Columns
属性返回一个Range
,Rows
属性也返回一个Range
。然而,前者的Range
会告诉For Each
它是一个“列的集合”,而后者的Range
将自己介绍为“行的集合”。
这是因为apparently在Range
类的每个实例中都有一个隐藏标志,这决定了Range
实例在For Each
中的行为。
查询Cells
时,要确保您得到的Range
实例将For Each
枚举模式设置为“单元格”。如果您一开始不打算使用For Each
范围,那么这种差异对您没有任何影响。
而且,即使您确实关心For Each
模式,在特定情况下,Range("A1").Resize(2,3)
和Range("A1").Resize(2,3).Cells
也是一样的,因为默认情况下,Range
是使用“单元格”的枚举模式构造的,而Resize
不会更改其调整大小范围的枚举模式。
因此,我唯一能想到的情况是,从已经存在的Cells
查询Range
会产生什么影响,当您有一个接受Range
作为参数的函数时,您不知道该Range
是如何构造的,您希望枚举该范围内的单个单元格,并且您希望确保是单元格For Each
将枚举,而不是枚举行或列:
function DoSomething(byval r as range)
dim c as range
'for each c in r ' Wrong - we don't know what we are going to enumerate
for each c in r.cells ' Make sure we enumerate cells and not rows or columns (or cells sometimes)
...
next
end function
发布于 2018-06-29 07:10:05
两者都有
Dim b As Variant
b = Range("A1").Resize(2, 3).Cells.Value
和
Dim c As Variant
c = Range("A1").Resize(2, 3).Value
将返回相同的值数组。所以它们是等价物。没有你使用的优势(一个更短)。
但你可以用
Range("A1").Resize(2, 3).Cells(1, 2).Value
让一个特定的细胞脱离这个范围。因此,这是您最有可能需要.Cells
on .Range
的地方。请注意,Cells(1, 2)
中的行/列编号相对于范围,而不是工作表的绝对编号。
所以不同之处是:
Range("A1:A2") 'range can return multiple cells …
Range("A1") '… or one cell.
Cells(1, 2) 'cells can return one cell or …
Cells '… all cells of the sheet
Range("A1:A2").Cells 'returns all cells of that range and therefore is the same as …
Range("A1:A2") '… which also returns all cells of that range.
Range("C5:C10").Cells(2, 1) 'returns the second row cell of that range which is C6, but …
Cells(2, 1) 'returns the second row cell of the sheet which is A2
https://stackoverflow.com/questions/51093274
复制相似问题