Marlon
Marlon

Reputation: 1877

Global variables not working on excel vba

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?

Upvotes: 1

Views: 3130

Answers (2)

David wyatt
David wyatt

Reputation: 318

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?

Upvotes: 3

Gary's Student
Gary's Student

Reputation: 96753

Your Immediate Window may not be high enough.

Based on Coleman's suggestion:

enter image description here

Upvotes: 2

Related Questions