Search code examples
excelvba

Is there a way to instantiate a new Control, without adding it to the UserForm?


I would prefer to create a Control object that does not belong to any particular Form, sort of as a proxy for other Form Control objects. The Control would need to be a TextBox.

I haven't used Visual Basic in many years, and have never touched VBA. So, my question isn't about whether or not this is advised, but rather whether it's even possible. :D

What I have now is:

Controls.Add("Forms.TextBox.1")

This however, adds the Control to the UserForm. Which is fine, I guess, because I can also just turn it invisible, but I'm just curious.

On the other hand, Dim ctl As New Control does not specify it should be a TextBox.

Where is the golden mean in between?


Solution

  • Gonna stick my neck out and say

    Dim o As MSForms.TextBox ' or Object if no reference to 'Microsoft Forms 2.0 Object Library'
    Set o = CreateObject("Forms.TextBox.1")
    o.Text = "Hello World"
    Debug.Print TypeName(o) & ", " & o.TextLength
    

    Prints TextBox, 11 to the Immediate window.