Home » excel » excel – How to set globals in a different module in VBA?

excel – How to set globals in a different module in VBA?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I created a global in a second module Module 2 so that i can make references in my Module 1 on those values
I tried the following

 Module 2 
 Global firstName As String

I have a couple of macros in Module 1

sub test ()
MsgBox firstName  'firstName is a global from Module 2
end sub

However, firstName was not recognized by any of my macros in Module 1 . How do I declare them correctly ? Do I need to create a sub in Module 2

How to&Answers:

You have to do following:

In Module2:

Global firstName As String

Sub M2_FN()
firstName = "Testing"
End Sub

Then in Module1:

Sub M1_FN()
Call M2_FN
MsgBox firstName  'firstName is a global from Module 2
End Sub

It works as you expected.

Answer:

In Module 2, I put:

Global firstname As String

Sub dural()
    firstname = "XXX"
    Call checkit
End Sub

In Module 1, I put:

Public Sub checkit()
    MsgBox firstname
End Sub

When I run dural, the correct text appears.