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
.