private variable: same module, other Sub/Function

G

Guest

By VB Help Private variables are: "Variables that are visible only to the
module in which they are declared."

I declared a private variable in a Sub in a module, and wanted to refer it
in a function (called from the Sub the variable was declared in) in the same
module, but I got a run-time error.

Do I misunderstand something, or what did I do wrong?
Stefi
 
R

Robin Hammond

Stefi,

declare the variable at the top of the module.

Option Explicit
Private strVar as string

Sub DoSomething()
Dim vRet as variant
vret = MyFunction()
End Sub

Function MyFunction() as variant
MyFunction = cvar(strVar)
End Function

Robin Hammond
www.enhanceddatasystems.com
 
G

Guest

Hi Stefi,

You need to declare the variable in the module - not within the sub routine.
Declare your private variable outside of a subroutine and then it'll work.


Good luck.
 
G

Guest

That was the problem, now it works.
Thanks,
Stefi


„Snake Plissken†ezt írta:
 
S

Snake Plissken

I suggest to declare variables before subs as follows

option explicit

dim var1, var2 as string
dim var3, var5 as integer
dim var4 as long
etc.

sub name_of_sub_1 ()
var1= "anystring"
.......
end sub

sub name_of_sub_2()
var3= 5
var5= 6
......
end sub

Function name_of_f(...)
'here u can "read" value of variables from subs and perform a function
end function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top