什么时候应该使用".Value"? [英] When should one use ".Value"
问题描述
我是Visual Basic的初学者,主要使用它来编辑MS Excel文件.
在复制/粘贴(单元格)内容或其他值时,有时会添加.value
.
何时应添加?
什么时候不?
有必要吗?
如果我在不需要的地方使用它,是否会损害我的代码?
在Excel VBA中,Range
对象是相当丰富的东西,它对应于一个单元格或一系列单元格.因此,它具有各种属性(位于给定的行中,可通过.Row
属性访问,它具有内部颜色,可能的边界线,公式等-均可通过点后的正确属性访问.)Value
是这些属性之一.它指的是单元格中的值-通常是数字或文本.使用Copy
和Paste
时将不会使用该方法,因为这些方法用于整个Range
对象-从它们能够复制格式而不仅仅是原始值的事实可以看出.>
您可以将一个单元格中的值分配.即使看起来像是复制/粘贴,它的确是完全不同的,并且在某种意义上说,当您要做的只是传递值时,这是一种技术含量较低的解决方案.可以使用例如Range("A1").Value = Range("B1").Value
或Range("A1") = Range("B1")
.后来工作的原因是Value
是Range
对象的默认属性-因此,在没有将Range
视为一个实际的对象.
就我个人而言,即使我可以依靠Value
这一事实,当我想要读取或设置一个单元格(或单元格范围)中的值时,我总是显式使用Value
是默认属性.大多数Excel VBA代码都大量使用Range对象和Range对象中的值.出于可读性考虑,最好让您的代码明确说明何时使用范围与何时使用值.如果在SO上遵循excel-vba
标记,您会发现程序员很少依赖Range的默认属性.
I'm a beginner with Visual Basic, and mainly use it to edit MS Excel files.
When copying/pasting (Cell) content or other values, in some cases .value
is added.
When should this be added?
When not?
Is it necessary?
Could it harm my code if I use it in places where it isn't needed?
In Excel VBA a Range
object is a fairly rich thing which corresponds to either a cell or a range of cells. As such it has all sorts of properties (it is in a given row, accessible via the .Row
property, it has interior color, possible borderlines, formulas, etc. -- all accessible via the right properties after the dot.) Value
is one of these properties. It refers to the value in the cell -- typically a number or a text. It wouldn't be used when using Copy
and Paste
since those methods are used on whole Range
object -- as can been seen by the fact that they are able to copy formatting and not just raw values.
You can assign the value in one cell to another. Even though this looks like copy/pasting it really is quite different and is in some sense a low-tech solution when all you want to do is transfer the values. It can be done using either e.g. Range("A1").Value = Range("B1").Value
or Range("A1") = Range("B1")
. The reason the later works is that Value
is the default property of a Range
object -- hence .Value
is implicit in any context in which you aren't treating the Range
as an actual object.
Personally, I always explicitly use Value
when I want to either read or set the value in a cell (or range of cells) even though I could rely on the fact that Value
is the default property. Most Excel VBA code makes heavy use of both Range objects and the values in the Range objects. For reasons of readability it is a good idea for your code to be explicit about when it is using the range vs. when it is using the value. If you follow the excel-vba
tag on SO you will see that it is relatively rare for programmers to rely on Range's default property.
这篇关于什么时候应该使用".Value"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!