如何使用 As in VBA 声明指定类型的多个变量?
How to declare multiple variables with specifying type using As in VBA?
根据this documentation by Microsoft,可以用下面的代码来确定;
a, b, and c are all Single; x and y are both Double
Dim a, b, c As Single, x, y As Double, i As Integer
> a, b, and c are all Single; x and y are both Double
这背后的逻辑如下
You can specify different data types for different variables by using a separate As
clause for each variable you declare. Each variable takes the data type specified in the first As
clause encountered after its variable name part.
然而,当我检查调试器或 MsgBox VarType(a)
输出时,情况并非如此。
如您所见,As
似乎只适用于它之前的变量,即 c
、y
和 i
。所有其他的都是 Variant/Empty 和 VarType
returns 0.
这只是文档有误,还是我遗漏了一些明显的东西?
Microsoft Visual Basic 应用程序 7.1.1056
Excel 2016 (Windows 10)
您链接到的文档没有错,但它是为 VB.NET 而不是 VBA 编写的。
在 VBA 中,如您所见,任何未紧跟 As <type>
的变量声明都将是 Variant
。
因此你需要写:
Dim a As Single, b As Single, c As Single, x As Double, y As Double, i As Integer
在VBA中,当你声明
Dim a, b, c As Single
它的作用相当于:
Dim a As Variant, b As Variant, c As Single
我认为最好的做法是始终在单独的行中声明变量。它可以防止此错误,还可以更快地扫描代码。所以代码看起来像这样:
Dim a As Single
Dim b As Single
Dim c As Single
根据this documentation by Microsoft,可以用下面的代码来确定;
a, b, and c are all Single; x and y are both Double
Dim a, b, c As Single, x, y As Double, i As Integer
> a, b, and c are all Single; x and y are both Double
这背后的逻辑如下
You can specify different data types for different variables by using a separate
As
clause for each variable you declare. Each variable takes the data type specified in the firstAs
clause encountered after its variable name part.
然而,当我检查调试器或 MsgBox VarType(a)
输出时,情况并非如此。
如您所见,As
似乎只适用于它之前的变量,即 c
、y
和 i
。所有其他的都是 Variant/Empty 和 VarType
returns 0.
这只是文档有误,还是我遗漏了一些明显的东西?
Microsoft Visual Basic 应用程序 7.1.1056 Excel 2016 (Windows 10)
您链接到的文档没有错,但它是为 VB.NET 而不是 VBA 编写的。
在 VBA 中,如您所见,任何未紧跟 As <type>
的变量声明都将是 Variant
。
因此你需要写:
Dim a As Single, b As Single, c As Single, x As Double, y As Double, i As Integer
在VBA中,当你声明
Dim a, b, c As Single
它的作用相当于:
Dim a As Variant, b As Variant, c As Single
我认为最好的做法是始终在单独的行中声明变量。它可以防止此错误,还可以更快地扫描代码。所以代码看起来像这样:
Dim a As Single
Dim b As Single
Dim c As Single