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
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
Procedure 2
Option Explicit
at the topIf 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).
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 theProject
. Declaring it with thePrivate
keyword will make it visible to all procedures in thatModule
.You are declaring it twice, if you add
Dim myVar as Double
in the functionmyFun
. The first time is with that line and the second line is in the parameters here: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:
In order to avoid the "Not declared error", you should declare
myVar
in theSub TestMe
and not in themyFun
function.