Well, yes of course you can write it each procedure. But No, No, No - it will not have the same effect as declaring it as Public. The value would never be passed from procedure to procedure.Instead of making it public I can write it in each procedure? Will this give me the same effect as declaring it public
As stated, a variable declared in a procedure only exists in that procedure. You can have 10 procedures with each one having a variable named myVar. Each myVar is absolutely independent of the others. They ONLY hold value within that procedure.
Take a look at this.[vba]Sub One()
Dim sVar As String
sVar = "Hello"
Call Two
MsgBox sVar
End Sub
Sub Two()
Dim sVar As String
sVar = "Goodbye"
End Sub[/vba]Two variables, both named sVar. What do you think the message will display? Let's run through.
In Sub One, sVar becomes "Hello", then control is passed to Sub Two. Yes, THAT sVar becomes "Goodbye". When Sub Two is terminated...so is the sVar in the procedure. Control is passed back to Sub One...and sVar is "Hello". It can NOT be changed by anything that happens in Sub Two, because Sub Two has its own scope.
[vba]Public sVar As String
Sub One()
sVar = "Hello"
Msgbox sVar ' displays "Hello"
Call Two
MsgBox sVar ' displays "Goodbye"
End Sub
Sub Two()
sVar = "Goodbye"
End Sub[/vba]Message box will display "Hello" then display "Goodbye" The scope of the variable is global, it is set for "Hello" in Sub One, then set for "Goodbye" in Sub Two.
You MUST look at Scope!