tags:

views:

91

answers:

2

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>?

+1  A: 

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
Gavin Miller
I work in Access and I can't 100% validate the code. But LFSR is certainly on the right track -- pass the calling object in as an argument of the function.
Smandoli
Thanks for the example!
Ryan Shannon
+1  A: 

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>
onedaywhen
Excellent example. Thanks!
Ryan Shannon