为什么VBA dim语句的行为会因声明的变量数而异?
如果我一次声明两个以上的变量,为什么VBA会将长变量类型转换为整数? 以下测试在前两种情况下产生长变量,但在第三种情况下产生整数类型为什么VBA dim语句的行为会因声明的变量数而异?,vba,variables,Vba,Variables,如果我一次声明两个以上的变量,为什么VBA会将长变量类型转换为整数? 以下测试在前两种情况下产生长变量,但在第三种情况下产生整数类型 Sub VarTest() Debug.Print "==Test1==" Dim j As Long: j = 1 Debug.Print "j is: " & VarType(j) End Sub Sub VarTest2() Debug.Print "==Test2==" Dim i, j As Long: j
Sub VarTest()
Debug.Print "==Test1=="
Dim j As Long: j = 1
Debug.Print "j is: " & VarType(j)
End Sub
Sub VarTest2()
Debug.Print "==Test2=="
Dim i, j As Long: j = 1
Debug.Print "j is: " & VarType(j)
End Sub
Sub VarTest3()
Debug.Print "==Test3=="
Dim i, j, k As Long: j = 1
Debug.Print "j is: " & VarType(j)
End Sub
在VBA中,当您声明
Dim a, b, c As Long
相当于:
Dim a As Variant, b As Variant, c As Long
您可以这样做来声明所有变量,只要:
Dim a As Long, b As Long, c As Long
必须单独指定每个变量的类型。如果未指定变量类型,则默认为
Variant
' AnyValue and MyValue are declared as Variant by default with values
' set to Empty.
Dim AnyValue, MyValue
' Explicitly declare a variable of type Integer.
Dim Number As Integer
' Multiple declarations on a single line. AnotherVar is of type Variant
' because its type is omitted.
Dim AnotherVar, Choice As Boolean, BirthDate As Date
如果你愿意,你可以用
样本:
DefLng I-Z
Sub VarTest3()
Dim i
Dim k As Integer
Dim s As String
Debug.Print "a is: " & VarType(a) 'variant
Debug.Print "i is: " & VarType(i) 'long
Debug.Print "j is: " & VarType(j) 'long
Debug.Print "k is: " & VarType(k) 'integer
Debug.Print "s is: " & VarType(s) 'string
End Sub
结果:
a is: 0
i is: 3
j is: 3
k is: 2
s is: 8
这就是它的工作原理
尺寸i,j,k As Long
与尺寸i As Variant,j As Variant,k As Long
相同-这不是将它们全部定义为Long
的快捷方式。它在您的情况下使用整数
,因为变量
会根据您输入的值转换为所需的最小类型。感谢您的清除。我以为我在文档中看到了这种语法,但我一定是在看Visual Basic而不是VBA。。。事实上,VBA意味着Visual Basic for Applications…@Brutus在这里您可以看到在VBA中声明变量的文档: