Ilan
Ilan

Reputation: 28

Set userform width from a module by looping through userforms

Been having a very frustrating problem that I can't seem to find a solution for anywhere - help would be greatly appreciated!

I know how to change the width of a userform from within the userform itself (Me.Width).

The problem is that I am writing a module that will format userforms dynamically. The module is passed a form and it does some manipulations on that form. So far everything works as long as I'm referring to objects on the form.

But I'm now trying to refer to the form itself, and when I try to change the width (of the form, not of a control on the form) I get the error: "Object doesn't support this property or method".

I've tried declaring it as both a UserForm and an Object and all of the other code works in both cases, but resizing the width doesn't. I can see in the immediate window that width isn't available, which is obviously why the code won't execute.

Here's the code that I've tried without succses:

Sub frmLoadLayoutTest()

frmLoadLayout frmTest
frmTest.Show

End Sub

Private Sub frmLoadLayout(frmActive As Object) 'Also tried (frmActive as UserForm)

'Setting the width of a control works
frmActive.Controls("labelTest").Width = 100 

'Setting the width of the form itself doesn't work
frmActive.Width = 100

End Sub

If anyone can provide an elegant solution, that would be fantastic. Alternatively, is there a way I can refer to the userform by name? (Something like Userform(frm1.name).Width = 100)

Thanks in advance!

Upvotes: 0

Views: 332

Answers (1)

Tim Williams
Tim Williams

Reputation: 166835

Try this:

Sub frmLoadLayoutTest()

    Dim frm As frmTest

    Set frm = New frmTest  '<<< create an instance of the form

    frmLoadLayout frm      '<<< pass in the instance
    frm.Show               '<<< show the instance

End Sub

Private Sub frmLoadLayout(frm As Object)
    With frm
        .Controls("labelTest").Width = 100
        .Width = 300
    End With
End Sub

See also why it's good practice to avoid the "default instance" and create your own explicit instance of a form before using it:

https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/

Upvotes: 1

Related Questions