0

How would you go about opening a form in another project from a form..

Lets say i have such a project structure:

  • p1
    • frm1
    • frm2
  • p2
    • frmxyz

opening frm1 from frmxyz in VB6...? Something like:

p1.frm1.show() 'Maybe?

How do you do it?

Olle Sjögren
  • 5,315
  • 3
  • 31
  • 51
Anshu Dwibhashi
  • 4,617
  • 3
  • 28
  • 59
  • Sorry for the trouble, i was working on a school project and i finally found a way to do it without opening a form from another project. Thanks to all who helped... – Anshu Dwibhashi Feb 07 '14 at 01:49

2 Answers2

3

There two different ways to resolve this issue:

1.) You can add frm1 to project p2, with project -> add form -> tab "existing". After that you can easily access with frm1.show().

2.) you create an interface object with a function to access the form compile the p1 as an active-x dll. in the next step, you can add the active-x dll as reference in p2 and show the form on calling the the function in the interface object.

thomas G
  • 123
  • 4
  • +1 for the second method. It has to support unloading all forms (in the separate `Forms` collection of the p2 project) for process tear-down purposes. – wqw Feb 09 '14 at 08:59
1

It's faily complicated. The easiest way I figured how to do it is the following :

Sub UseExternalUserForm()

    'Set the File name, File path, and Form name
    Dim myForm As String, myDirectory As String, myFile As String
    myDirectory = "C:\FilePath\"
    myFile = "MyFile.xls"
    myForm = "UserForm1"

    'Start dealing with workbooks and their objects
    Dim vbc As Object
    Dim wb1 As Workbook, wb2 As Workbook
    Set wb1 = ThisWorkbook
    Set wb2 = Workbooks.Open(myDirectory & myFile)

    If UserFormExists(2, myForm) Then
        'Export the form if it exists
        wb2.VBProject.VBComponents(myForm).Export (myForm & ".frm")
    Else
        'Display an error message if it doesn't
        MsgBox myForm & " doesn't exist in " & wb2.Name
    End If

    wb2.Close False

    If UserFormExists(1, myForm) Then
        'Display an error message if it already exists
        MsgBox myForm & " already exists in " & wb1.Name
    Else
        'Import the form if it doesn't
        Set vbc = Application.VBE.vbProjects(1).VBComponents.Import(myForm & ".frm")
        VBA.UserForms.Add(myForm).Show

        'Remove the imported form
        Application.VBE.vbProjects(1).VBComponents.Remove vbc
    End If

End Sub


'How to figure out if a form already exists in a project (numbered with an integer representing the index
'           of the project in the VBAProject Explorer)
Public Function UserFormExists(projectIndex As Integer, formName As String) As Boolean

    On Error Resume Next
        UserFormExists = (Application.VBE.vbProjects(projectIndex).VBComponents(formName).Name = formName)
    On Error GoTo 0

End Function

Let me know if you need any extra explanations as to how to get this code to work for you.

Bernard Saucier
  • 2,240
  • 1
  • 19
  • 28