Global variables not working on excel vba - 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?

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?

Your Immediate Window may not be high enough.
Based on Coleman's suggestion:

Related

Getting 'SubScript Out of Range' Error in VBA when calling class Method

I'm going to try to lay out this issue in as much detail as possible. Apparently I can't post images, as I am a New Member...So I will try to describe my situation as good as I possibly can.
So, I am working with a custom class called "Shifts". I have this class declared and set up in a Class Module in VBA. I declare an instance of the "Shifts" class inside a normal Module and call it "Shift".
Dim Shift As New Shifts
My "Shifts" class has 4 variables (String Arrays):
Private ShiftMembers() As String
Private ShiftCallSigns() As String
Private ShiftAssignments() As String
Private ShiftStatuses() As String
I have written a Sub within the class called "Clear" to clear the data in these variables (via ReDim):
Public Sub Clear()
ReDim ShiftMembers(-1) As String
ReDim ShiftCallSigns(-1) As String
ReDim ShiftAssignments(-1) As String
ReDim ShiftStatuses(-1) As String
End Sub
Now, when I call the Clear Sub of the "Shifts" class (declared as "Shift"):
Shift.Clear 'This is called from within the Module.
i get Subscript out of range (Error 9). My class is declared at the very top of the module, outside of any methods or functions. The Clear() sub within my class is declared Public. I don't understand why I can't seem to access my Clear Sub properly.
Any help would be greatly appreciated!
-Rob
I don't know if you can use ReDim that way. From the documentation, the subscripts argument is bound by the Option Base statement:
subscripts
Required
Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax: [lower To] upper [,[lower To] upper] . . . When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
The Option Base statement must be either 1 or 0, and -1 is out of bounds, so the error makes sense.
In order to clear your arrays use the Erase command instead of ReDim.
I put this in my class module (I use the _Initialize procedure just to make one of the array's non-empty, in order to verify that Erase did its job):
Private ShiftMembers() As String
Private ShiftCallSigns() As String
Private ShiftAssignments() As String
Private ShiftStatuses() As String
Sub Class_Initialize()
ReDim ShiftMembers(1 To 2)
End Sub
Public Sub Clear()
Erase ShiftMembers
Erase ShiftCallSigns
Erase ShiftAssignments
Erase ShiftStatuses
End Sub
I use the following to test:
Sub t()
Dim s As New Shift
s.Clear
End Sub

VBA use global variable in userform code

I'm working in Excel 2010 VBA. Is there a way of accessing values in global variables declared outside a userform, in code inside the userform? Code inside my userform returns the global variable as null - can't work out why!
The variable is declared in the ThisWorkbook module as:
Public TargetCell As Range
Public TargetCellWorksheet as Worksheet
Public CurrentValue As Long
Inside the userform, I have this code on the "Update" button:
Private Sub Update_Click()
MsgBox ("Start of Update sub. TargetCellWorksheet =" & TargetCellWorksheet)
End Sub
The msgbox returns "" for the variable.
Hoping someone may be able to help me understand this and how to access the variable inside the userform? Thank you in advance
As for the problem itself, you declare
Public TargetCellWorksheet as Worksheet
and then try to show it into a MsgBox:
MsgBox ("Start of Update sub. TargetCellWorksheet =" & TargetCellWorksheet)
Did you maybe mean TargetCellWorksheet.Name, or TargetCellWorksheet.Range("A1").Value, since the MsgBox expects to receive a string?
However, if you're sure about your code, it might depend on the fact that the variable is not properly declared as Public and it goes at module level only. You might want to add a property to your form, if the variable is part of the form itself (I assume that you meant to use CurrentValue, but you can simply change the type of the property from Long to Worksheet and use it instead):
This goes inside the code of your form
Dim pCurrentValue As Long
Public Property Get CurrentValue() As Long
CurrentValue = pCurrentValue
End Property
Public Property Let CurrentValue (value As Long)
pCurrentValue = value
End Property
Hence, passing the variable from the module to the form like this:
This goes into your module, before you enter the code of the form
Dim myForm As New yourForm
myForm.CurrentValue = whateverYourVariableIs
and so using the variable inside your form like this:
You can hence use your variable by calling it from the property of the form
myVariableInTheForm = Me.CurrentValue
I must say that, however, it is strange that a public variable is not reaching the stack of the form. Are you sure you're not only declaring the variable without assigning any value before?

Global variable resets when adding a command button with code

I have this short piece of code
Public n As Integer
Public Sub Foo()
For i = 0 To 4
MyModule.n = MyModule.n + 1
Next i
End Sub
which is defined in a Module named MyModule. This code is working as expected: After executing for the first time 'MyModule.n' has the value 5. After executing the second time it has the value 10 and so on.
When I extend the code, to add a CommandButton and place it onto the working sheet, the global variable MyModule.n loses it's value on every new call of Foo:
Public n As Integer
Public Sub Foo()
Dim btn As OLEObject
For i = 0 To 4
Set btn = Worksheets("Aufträge").OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
Left:=122, Top:=321, Width:=30, Height:=30)
MyModule.n = MyModule.n + 1
Next i
End Sub
The code seems to work because the command button is created and placed correctly. Why does the global variable reset if executing the second code fragment?
Furthermore I can't place a break point after or inside the For-Loop in the second code fragment. I get the message Can't enter break mode at this time.
Based on the search I did & my conclusion is that you can't add controls dynamically to the worksheet and retain the state of variables.
Here is why: Adding a button will force the sheet to goto design mode & hence reset of variables.
Supporting links
http://www.pcreview.co.uk/forums/dynamically-adding-activex-controls-via-vba-kills-global-vba-heap-t3763287p2.html
https://web.archive.org/web/20101215134333/http://support.microsoft.com/kb/231089 (originally //support.microsoft.com/kb/231089)
You don't need to use a for next loop for the first example. Why don't you do that :
Public n As Integer
Public Sub Foo()
MyModule.n = 5
End Sub
This will do the thing in one operation.
In the second example you don't add one button, you add 5 of them. Check the help fo "For Next".

VBA Excel "Variables are required"

Got a trouble in a VBA excel program.
Sub code(s)
...
code = t
End Sub
And then :
Sub CommandButton1_Click()
...
For i = 0 To size
current_y = code(string_array(i))
...
End Sub
When i run the program, i got this error "Variables are required" (not sure, i'm working on a japanese version of excel). Sub CommandButton1_Click is highlighted and code is selected inside CommandButton1_Click. Can't figure out why, though it must be simple...
You're trying to return a result from a Sub. Try declaring it as a function instead, as this is able to return values to the caller:
Function code(s)
...
code = t
End Function
If it makes it any clearer, on my English version the error message is:
Expected Function or variable
Does the code include Option Explicit? Perhaps the error translates to "Variable declaration required"? Try removing option explicit - if that fixes it remove that line, then go through checking all variables are declare (e.g. dim current_y as string).

Why does my function's name appear twice in the "locals" window?

I have created a Class Module in which I have defined a function. Whenever that function is called, it is listed twice in the locals window. Only the second one's value changes, the first one stays either empty or "zero", depending on its type, until the end of the code's execution. I don't have this problem with functions defined in standard modules. Did I do something wrong, is this a bug, or is there a logical reason behind this?
Contents of the TestClass class module:
Public Value As Double
Function AddFive() As Double
AddFive = Me.Value + 5
End Function
Contents of the standard module:
Sub TestSub()
Dim TestObject As New TestClass
TestObject.Value = 2
MsgBox TestObject.AddFive
End Sub
Here is a screenshot showing that, when the code is executed line-by-line, the function's value is listed twice in the locals window, and only the second value has changed after the function's code was executed.
(link to screenshot)
I'm using VBA for Excel 2010.
Thanks in advance.
The issue is more in how you are doing it. If you have a function that just adds 5 to an internal variable of a class object, then it's technically a void (Sub in VBA) since you don't need a return value.
Your code should be:
CLASS
Public Value As Double
Sub AddFive()
Me.Value = Me.Value + 5
End Sub
MODULE
Sub test()
Dim testObject As New TestClass
testObject.Value = 2
testObject.AddFive
MsgBox testObject.Value
End Sub
I can imagine there could be a number of reasons why there are 2 variables created, but I find it a bit pointless to go into why there is unexpected behavior since you are doing improper code.
If you want, you can even write class function that will show it's value + 5 in a msgbox and this would not create an extra variable either. But that is strange and I think you want the code above. But here it is regardless:
CLASS
Public Value As Double
Sub ShowPlusFive()
MsgBox Me.Value + 5
End Sub
MODULE
Sub test()
Dim testObject As New TestClass
testObject.Value = 2
testObject.ShowPlusFive
End Sub