VBA 隐式和显式声明
示例
如果代码模块不包含OptionExplicit在模块顶部,则编译器将在使用它们时自动(即“隐式”)为您创建变量。它们将默认为变量类型Variant。
Public Sub ExampleDeclaration()
someVariable = 10 '
someOtherVariable = "Hello World"
'Both of these variables are of the Variant type.
End Sub在上面的代码,如果OptionExplicit指定,代码将中断,因为它缺少必要Dim的陈述someVariable和someOtherVariable。
Option Explicit
Public Sub ExampleDeclaration()
Dim someVariable As Long
someVariable = 10
Dim someOtherVariable As String
someOtherVariable = "Hello World"
End Sub最好的做法是在代码模块中使用OptionExplicit,以确保声明所有变量。
请参见VBA最佳做法,默认情况下如何设置此选项。