VBA defining variables

J

Jeff

Hi

I have the code below. I set JJ=33, and I need Macro5 and Macro6 to use the
variable JJ. But when it goes into those macros JJ is empty. Do you know
how to fix this?

Sub TestMacro2()
Dim JJ As Double
JJ = 33
Call Macro5
Call Macro6
End Sub

Thanks for your help
 
B

bpeltzer

Because the variable is declared inside the sub TestMacro2, its 'scope' is
limited to that sub. to make it more widely available you can either declare
it outside the sub (making it 'global', which is easy but not appreciated by
the programming gurus) or make it an argument to Macro5 and Macro6 (ex:
declare Sub Macro6(InputVar as double) ... End Sub, and call that as
Macro6(JJ33).
--Bruce
(BTW, to find such errors earlier, you should set VBA to require that
variables be declared; 'Option Explicit' should appear at the beginning of
each module).
 
D

Dave Peterson

One way is to pass the value:

Sub TestMacro2()
Dim JJ As Double
JJ = 33
Call Macro5(jj)
Call Macro6(jj)
End Sub

sub macro5(myVal as double)
msgbox myVal
end sub

sub macro6(myothervalue as double)
msgbox myothervalue
end sub
 

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