问题
I have the following problem:
Option Explicit
is used.
the code
Function myFun( myVar as Double) as double
myVar = myVar + 1
end function
throws an error that myVar
is not defined
however, if I add the line Dim myVar as Double
it says that the variable is declared twice.
What am I doing wrong?
Thanks
回答1:
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
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.
I suppose your code looks like this:
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
In order to avoid the "Not declared error", you should declare myVar
in the Sub TestMe
and not in the myFun
function.
回答2:
Based on your comment to Vityata's question, let me try a slightly different way of explaining things.
You need to think about the Scope of the variable.
Consider that you have two separate procedures:
Procedure 1
Public Sub TestMe()
Dim myVar As Double
myVar = 5
Debug.Print myFun(myVar)
End Sub
Procedure 2
Function myFun(myVar As Double) As Double
myFun = myVar + 1
End Function
- The module has
Option Explicit
at the top - Your variables are defined within each procedure
- The scope of the variable is the procedure
- Therefore, each variable needs to be declared within each procedure.
- Even though they have the same names, since the scope of the variable is only within the procedure, they are not the same variables.
If you want to declare a variable, and have it be the same variable in more than one procedure, you need to declare it a module level (for example).
Option Explicit
Public myVar As Double
Public Sub TestMe()
myVar = 5
myFun myVar
Debug.Print myVar
End Sub
Function myFun(myVar) As Double
myVar = myVar + 1
End Function
Note also in the two different modules, the Function
and the call to the function are subtly different.
As an aside, declaring the variable with the Public
keyword at the module level will make it visible to all procedures within the Project
. Declaring it with the Private
keyword will make it visible to all procedures in that Module
.
来源:https://stackoverflow.com/questions/46930209/vba-problems-with-defining-variables-in-function-if-option-explicit-is-used