Ryan Shannon
Ryan Shannon

Reputation: 710

How to tell which form module called your class

Suppose, for instance, that I want a method that adds a ComboBox. Maybe I try this

Public Sub AddComboBox()
    Dim cb As MSForms.ComboBox

    Set cb = <Calling form module>.Controls.Add("Forms.ComboBox.1")
End Sub

How can I get <Calling form module>?

Upvotes: 0

Views: 321

Answers (2)

onedaywhen
onedaywhen

Reputation: 57073

As others have said, pass the instance of the form to class method. Unlike others, I'm going to add:

  • Declare the argument AS MSForms.UserForm
  • Pass the parameter ByVal.
  • If calling from the UserForm itself, use the Me keyword in the call.

He's a brief example:

' <Module1.bas>
Option Explicit
Sub Main()

  UserForm1.Show vbModeless
  UserForm2.Show vbModeless

End Sub
' </Module1.bas>

' <UserForm1.frm>
Option Explicit

Private Sub UserForm_Activate()
  Dim c As Class1
  Set c = New Class1
  c.AddComboBox Me
End Sub
' </UserForm1.frm>

' <UserForm2.frm>
Option Explicit

Private Sub UserForm_Activate()
  Dim c As Class1
  Set c = New Class1
  c.AddComboBox Me
End Sub
' </UserForm2.frm>

' <Class1.cls>
Option Explicit

Public Sub AddComboBox(ByVal MSForms_UserForm As MSForms.UserForm)
    Dim cb As MSForms.ComboBox    
    Set cb = MSForms_UserForm.Controls.Add("Forms.ComboBox.1")
End Sub
' </Class1.cls>

Upvotes: 1

Gavin Miller
Gavin Miller

Reputation: 43855

I think you're writing this the wrong way. Instead of trying to determine who called the method, just pass the <Calling Form Module> to AddComboBox() as an argument. Like this:

Public Sub CallToAddComboBox()
    AddComboBox(<Calling form module>)
End Sub

Public Sub AddComboBox(CallingFormModule as <Module Object Type>)
    Dim cb As MSForms.ComboBox

    Set cb = CallingFormModule.Controls.Add("Forms.ComboBox.1")
End Sub

Upvotes: 1

Related Questions