【问题标题】:What is the difference between 'Type characters' and 'Type conversion functions' in VBA?VBA中的“类型字符”和“类型转换函数”有什么区别?
【发布时间】:2021-06-20 03:16:28
【问题描述】:

从我对VBA的理解来看,Type charactersMS Docs - Type characters)似乎主要用于变量的声明过程中,以缩短代码行并使用隐式声明,同时仍然强制数据输入。

另一方面,类型转换函数MS Docs - Type conversion functions)主要用于计算和值转换,以确保变量之间的类型兼容性。

但我已经看到 type characters 被用在 type 转换函数 的公式中。那么这两种方法有什么区别呢?我应该使用哪一个以及何时使用?最佳做法是什么?

比如下面代码中b的每次计算有什么区别:

Dim a As Integer, b As Double
a = 4
b = a# * 10.0
b = a * 10#
b = CDbl(a * 10)
b = CDbl(a) * CDbl(10)

如果这个问题是愚蠢的,或者如果这个问题已经在这个网站的某个地方得到了回答,请原谅我。

【问题讨论】:

标签: excel vba casting type-conversion


【解决方案1】:

声明变量或函数时,类型字符是显式而非隐式选项。它们只是As Datatype 的一个更晦涩、更不受欢迎的版本。

使用变量或函数时,完全不需要类型字符。它们可以作为个人喜好保留,但是它们必须与声明变量的类型相匹配(这就是为什么它们首先不需要),并且声明是否使用 @987654325 并不重要@ 或As Double。然而,在这种情况下,代码开始看起来和感觉像 QBasic
一个值得注意的例外是some built-in functions 的使用,它具有VariantString 两种风格。在此处指定 $ 会有所不同。

当声明字面量时,为什么有人想将字面量降级为函数调用?这样做的唯一结果是代码变慢,让未来的开发人员感到困惑,并且无法将表达式的结果保存在 Const 中,所以当你想要一个 10-as-a-Double 时,10# 远远优于CDbl(10),就像#10/19/2012 11:34:06 AM# is 大大优于CDate("2012-10-19 11:34:06")

【讨论】:

  • 非常感谢!您的解释和链接非常有帮助。
  • 在第 3 段中,当比较 10#CDbl(10) 时,CDbl 的超时是否是由于为比最初声明的更大的变量重新分配内存的过程? (Integer 为 2 个字节,Double 为 8 个字节)
  • 不,这是因为与没有调用相比,它被调用了。
【解决方案2】:

请看下一个 Sub 示例和每一行 cmets:

Sub testTypeCharConv()
 Dim a As Integer, b As Double
 a = 4.2                     'in order to see how Integer declaration trunks the decimals
 'b = a# * 10.2              'this will raise an error, since the variable has already been declared
 b = a * 1000                'it returns correct 4000 (4.2 is rounded at 4, being an Integer)
 'b = a * 10000              'Overflow error, because of Integer maximum value of 32,767
   b = a * 10000#            'returns 40000 due to Double conversion, the result is converted to Double
 b = CDbl(a) * 1000          'it does not change anything. 4.2 has already been trunked to 4
  b = CDbl("4.2") * 1000     'returns 4200, CDbl converting a string to a double
  b = a * 10.2               'returns 40.8
 b = CDbl(a) * CDbl(10.2)    'both conversions do not help in any way
End Sub

【讨论】:

  • 感谢您对每个案例的解释。我总是对某些语言如何将隐式类型转换为最精确的数据类型感到惊讶,而另一些语言则坚持显式声明变量。
猜你喜欢
  • 2013-12-27
  • 1970-01-01
  • 2011-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
相关资源
最近更新 更多