Set object whit a variable name

I want to make a function who get a param name and will create a object whit this name ex.:

'my sub:
Sub CreateObj(UserId as integer)
   Dim "UserId" & UserId as MyObject
   SET "UserId" & UserId = New MyObject
End Sub

if i send 10 to the function this will make the same thing than:

Dim UserId10 as MyObject
SET UserId10 = New MyObject

How can i make my sub for it works ?
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

TimCotteeConnect With a Mentor Commented:
You cannot do this in quite the way you describe. You can however declare an array of objects and reference them like that:

Dim aryMyObjects(10) As MyObject

Sub CreateObj(UserID As Integer)
  Set aryMyObjects(UserID) = New MyObject
End Sub

Or with a collection

Dim colMyObjects As Collection

Private Sub Form_Load()
  Set colMyObjects = New Collection
End Sub

Sub CreateObject(UserID As Integer)
  Dim NewObject As MyObject
  Set NewObject = New MyObjects
  colMyObjects.Add NewObject,UserID
End Sub

You can then refer to the created object using

Why would you want to do this?

Names that you give to variables are used only from within your source code, not in the compiled binary (except for debugging information). Dynamically generating variable names is only useful for Add-Ins and code generators.

If you need to be able to discern between objects, I suggest you add a property to your class that stores the User ID as mentioned in your example. Assuming you call the property "UserID", then you can code your creation function as follows:

   Function CreateObj(UserId as integer) As MyObject
      Set CreateObj = New MyObject
      CreateObj.UserID = UserID
   End Sub

Use the function like this:

   Dim O As MyObject
   Set O = CreateObj(10)

To inspect the User ID of any MyObject instance, use the property as in:

   If O.UserID = 10 Then ...

Optionally, you could store the created objects in a collection:

   Dim MyObjects As Collection

   Function CreateObj(UserID As Integer) As MyObject
      Set CreateObj = New MyObject
      CreateObj.UserID = UserID
      MyObjects.Add CreateObj, CStr(UserID)
   End Sub

so you can enumerate them:

   Dim O As MyObject
   For Each O in MyObjects
      Debug.Print O.UserID
   Next O

and retrieve one by it's UserID:

   Dim O As MyObject
   Set O = MyObjects.Item("10")

This way, you don't need to declare a variable for each object instance you're application requires, because you can retrieve the required instance from the collection into a temporary variable of the type MyObject.

All Courses

From novice to tech pro — start learning today.