1

I'm trying to use global variables in a excel macro I'm creating, but i can't get them to work. I wrote te following code:

Public globalVar As Integer

Public Sub TestGlobal()
    SetGlobalVar

    GetGlobalVar
End Sub

Public Sub SetGlobalVar()
    globalVar = 5
End Sub

Public Sub GetGlobalVar()
    Debug.Print "globalVar = "
    Debug.Print globalVar
End Sub

I expected this code to show globalVar = 5, but it's showing globalVar =, and when I put the mouse over the globalVar variable in SetGlobalVar it shows "5", but when I do that on GetGlobalVar, it shows "Empty".

What am I doing wrong? Shouldn't the value be the same, since the variable is global?

2
  • Running TestGlobal here prints globalVar = then 5 on the next line as expected. Right click globalVar in the declaration line and add watch then you can debug line by line and see how its value is changing. Commented Jan 27, 2018 at 11:48
  • Why not simply Debug.Print "globalVar = " & globalVar ? Commented Jan 27, 2018 at 14:38

2 Answers 2

3

When i run the code it works, just to check you are declaring the public variable at the top of the module and not after another sub?

Sign up to request clarification or add additional context in comments.

2 Comments

Thats exactly it. I've already changed to 'Debug.Print "globalVar = " & globalVar', and it continued to show empty. But when i moved the global variable declaration to the top of the file it worked.
Glad I could help
2

Your Immediate Window may not be high enough.

Based on Coleman's suggestion:

enter image description here

1 Comment

That is a very good guess as to the source of OP's confusion. Since the code is so straightforward and works as expected, I couldn't figure out why he thought that there was a problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.