如何在VBA中使用As指定类型来声明多个变量?

问题描述 投票:2回答:2

根据this documentation by Microsoft,以下代码可用于确保;

a,b和c都是Single; x和y都是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  

这背后的逻辑如下

您可以为声明的每个变量使用单独的As子句为不同的变量指定不同的数据类型。每个变量采用在其变量名称部分之后遇到的第一个As子句中指定的数据类型。

但是,当我使用调试器或MsgBox VarType(a)输出检查时,情况并非如此。

enter image description here

正如你所看到的,As似乎只适用于它之前的变量,即cyi。所有其他都是Variant / Empty,VarType返回0。

这只是文档错误,还是我遗漏了一些明显的东西?

Microsoft Visual Basic for Application 7.1.1056 Excel 2016(Windows 10)

excel vba declaration variable-declaration
2个回答
5
投票

您链接到的文档没有错,但它是为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

1
投票

在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
© www.soinside.com 2019 - 2024. All rights reserved.