为什么要在VBA或Excel中使用DIM语句? [英] Why should I use the DIM statement in VBA or Excel?
问题描述
因此,在上有一个问题什么 DIM
是,但是我找不到为什么要使用它.
So there is a question on what DIM
is, but I can't find why I want to use it.
据我所知,我看不出这三组代码之间的区别:
As far as I can tell, I see no difference between these three sets of code:
'Example 1
myVal = 2
'Example 2
DIM myVal as Integer
myVal = 2
'Example 3
DIM myVal = 2
如果我省略了DIM
,代码仍然运行,并且在经过2或3个嵌套循环之后,如果忽略它们,我的输出不会有任何差异.来自Python,我喜欢保持代码整洁*.
If I omit DIM
the code still runs, and after 2 or 3 nested loops I see no difference in the output when they are omitted. Having come from Python, I like to keep my code clean*.
那我为什么要用DIM
声明变量?除了样式方面的考虑之外,使用DIM
是否有技术上的理由?
So why should I need to declare variables with DIM
? Apart from stylistic concerns, is there a technical reason to use DIM
?
*我也很懒,出于声明变量的习惯.
推荐答案
未声明使用的任何变量的类型均为Variant
.尽管变体在某些情况下很有用,但在不需要时应避免使用它们,因为它们:
Any variable used without declaration is of type Variant
. While variants can be useful in some circumstances, they should be avoided when not required, because they:
- 慢一点
- 使用更多的内存
- 通过拼写错误或通过分配错误的数据类型的值,更容易出错
这篇关于为什么要在VBA或Excel中使用DIM语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!