I am using vba for the first time in a internship, so maybe this is basic but I can’t seem to make my variables public… I have tried to create a global module where I declare them as public, the ones I want to use in other places besides the UserForms where they are being used now.
I am sensing the problem is that most of them are lists so I had to set them as so, example:
Set lst = CreateObject("System.Collections.ArrayList")
what I have in globalvars:
Public lst2 As Object
Public lst3 As Object
Public total As Variant
Public densl As Object
Public densal As Object
Public rtl As Object
Public cascal As Object
Public na2ol As Object
Public clo2l As Object
I have the majority of them set as I explained before, all of whom are described as objects
But if I for example run this test
Sub Example_Use_List()
Dim i As Integer
For i = 0 To lst2.Count - 1
Debug.Print "Value in lst2: " & lst2(i)
Next i
MsgBox "The total value is: " & total
End Sub
It immediately tells me that the variable is not defined
7
That is the problem with working with Public variables. It’s hard to say where and when they are set or unset. It is best to pass the variables as parameters. Whenever you click Reset (Stop Button) in the VBA editor all the variables are unset. BTW, ArrayLists are great but they are not available on all machines.
There is no enough context to know exactly what is wrong. Checking to see if the object is set is the best that I can do.
Option Explicit
Public lst2 As Object
Public lst3 As Object
Public Total As Variant
Public densl As Object
Public densal As Object
Public rtl As Object
Public cascal As Object
Public na2ol As Object
Public clo2l As Object
Sub lst2_InitExample()
Set lst2 = CreateObject("System.Collections.ArrayList")
Dim n As Long
For n = 1 To 20
lst2.Add n
Next
End Sub
Sub Example_Use_List()
Dim n As Long
Dim Total As Double
' Check if lst2 is Nothing before proceeding
If lst2 Is Nothing Then
MsgBox "lst2 is not initialized.", vbExclamation
Exit Sub
End If
' Loop through each item in lst2 and print its value in the Immediate Window
For n = 0 To lst2.Count - 1
Debug.Print "Value in lst2: " & lst2(n)
Next
' Convert lst2 to an array and sum its values
Total = Application.Sum(lst2.ToArray)
' Display the total value in a message box
MsgBox "The total value is: " & Total
End Sub