VBA:如果使用Option Explicit,则在函数中定义变量的问题 [英] VBA: problems with defining variables in function if Option Explicit is used
问题描述
我有以下问题:
Option Explicit
.
代码
Function myFun( myVar as Double) as double
myVar = myVar + 1
end function
引发错误,提示未定义 myVar
throws an error that myVar
is not defined
但是,如果我将行 Dim myVar添加为Double
,则表示变量被声明了两次.
however, if I add the line Dim myVar as Double
it says that the variable is declared twice.
我在做什么错了?
谢谢
推荐答案
如果在函数 myFun
中添加 Dim myVar作为Double
,则需要声明两次.第一次使用该行,第二行在此处的参数中:
You are declaring it twice, if you add Dim myVar as Double
in the function myFun
. The first time is with that line and the second line is in the parameters here:
Function myFun( myVar as Double) as double
与 Option Explicit
没有任何关系,不允许您在同一范围内声明两个具有相同名称的变量.
That does not have anything to do with Option Explicit
, you are not allowed to declare two variables with the same name in the same scope.
我想您的代码如下:
Option Explicit
Public Sub TestMe()
'dim myVar as double (uncomment to avoid the error)
myVar = 5
Debug.Print myFun(myVar)
End Sub
Function myFun(myVar As Double) As Double
myVar = myVar + 1
End Function
为了避免出现未声明的错误",应在 Sub TestMe
中而不在 myFun
函数中声明 myVar
.
In order to avoid the "Not declared error", you should declare myVar
in the Sub TestMe
and not in the myFun
function.
这篇关于VBA:如果使用Option Explicit,则在函数中定义变量的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!