Results 1 to 26 of 26

Thread: How To Call a Form When Form Name is a String Variable

  1. #1

    Thread Starter
    New Member
    Join Date
    Sep 2009
    Posts
    11

    How To Call a Form When Form Name is a String Variable

    I've written a database-driven menu system in VB6 in which the form names that need to be called (when a user selects the report they want run) are strings contained in database. How do I call that form so it loads if the form name is a string? I don't believe CallByName will work, but I'm open to being wrong on that.

    [BTW: I'm not willing to load all of my forms and then hide them so they're accessible. I have too many forms for that solution to be practical.]

    I will also need to pass parameters to the Form such as Caption. Since the Form name is contained inside a string, how can I reference the Caption property? Also, we use a public string in each form called RunReport which allows us to pass a string identifying which code in the form we want to execute. This allows us to use one form for many different reports.

    I tried to create a form object using the code below where sFormName is the name of the form passed to the function as a string:
    Code:
    Dim oForm As Form
    Set oForm = Forms.Add(sFormName)
    Load oForm
    oForm.Show
    however as soon as I set the object by using "Set oForm = Forms.add(sFormName)", VB kicks off that form's Form_Load routine. So I don't have the opportunity to set the public variable RunReport prior to Form_Load being executed. Any ideas on how to achieve my goal would be very much appreciated.

    Thanks

  2. #2
    PowerPoster
    Join Date
    Oct 2002
    Location
    British Columbia
    Posts
    9,758

    Re: How To Call a Form When Form Name is a String Variable

    What code do you have in Form_Load? You should be able to move it elsewhere giving you more control over when things are executed.

  3. #3
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    Re: How To Call a Form When Form Name is a String Variable

    You could move the code to the Form_Paint event using code similar to this:
    Code:
    Private Sub Form_Paint()
        Static haveInitilized As Boolean
        If Not haveInitilized Then
            haveInitilized = True
            'Your init code goes here
        End If
    End Sub

  4. #4

    Thread Starter
    New Member
    Join Date
    Sep 2009
    Posts
    11

    Re: How To Call a Form When Form Name is a String Variable

    Thanks for the suggestion, Bruce, but the existing forms can't be changed. There are 40-50 forms in a reporting system that's been working for many years. I'm not going to tear it all apart. There must be a better way. Thanks.

  5. #5

    Thread Starter
    New Member
    Join Date
    Sep 2009
    Posts
    11

    Re: How To Call a Form When Form Name is a String Variable

    Thanks, Joacim. If I'm not mistaken, the Form_Paint event is fired AFTER the Form_Load so that wouldn't work. If I misunderstood your answer, please let me know. The best solution would not force me to change 40-50 forms, though. Rather than changing the forms, I would like to be able to call the form using string variable from my database (ie: form name, caption, runreport (as stated earlier), etc.).

  6. #6
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: How To Call a Form When Form Name is a String Variable

    Would it make any difference if the Form_Load code is called twice? If not then you can do things like this:

    Code:
    Dim oForm As Form
    Set oForm = Forms.Add(sFormName)
    
    oForm.Caption = "whatever"
    oForm.RunReport = "something"  
    oForm.Form_Load
    
    oForm.Show
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog • 101 LINQ Samples • JSON Validator • XML Schema Validator • "How Do I" videos on MSDN • VB.NET and C# Comparison • Good Coding Practices • VBForums Reputation Saver • String Enum • Super Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  7. #7
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: How To Call a Form When Form Name is a String Variable

    A less dynamic approach, but should solve the immediate problem.
    Build a routine that simply uses Select Case for the passed form name. Only need to be created once and only updated when forms are added, deleted or renamed.
    Code:
    Public Function LoadTheForm(formName As string) As Form
    Dim formRef As Form
    Select Case LCase$(formName)
       Case "form1": Set formRef = New Form1
       Case "form2": Set formRef = New Form2
       Case "form3": Set formRef = New Form3
       ' etc
    End Select
    Set LoadTheForm = formRef
    End Function
    A sample call migh look like:
    Code:
    Set oForm = LoadTheForm(sFormName)
    oForm.RunReport = "QuarterlyEarnings"
    Load oForm
    oForm.Show
    You said you weren't willing to modify 50+ forms, but if you are willing to add one public function to a module, this might be your answer.
    Last edited by LaVolpe; Sep 10th, 2009 at 02:10 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  8. #8
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    Re: How To Call a Form When Form Name is a String Variable

    Quote Originally Posted by edperlstein View Post
    Thanks, Joacim. If I'm not mistaken, the Form_Paint event is fired AFTER the Form_Load so that wouldn't work. If I misunderstood your answer, please let me know. The best solution would not force me to change 40-50 forms, though. Rather than changing the forms, I would like to be able to call the form using string variable from my database (ie: form name, caption, runreport (as stated earlier), etc.).
    The problem is that you can't change the Caption or any other properties of a Form without it being loaded.

    So if you have code in Form_Load that you don't want to run before you have set a lot of properties then you have no choice but to move that code from Form_Load to somewhere else.

  9. #9
    PowerPoster
    Join Date
    Oct 2002
    Location
    British Columbia
    Posts
    9,758

    Re: How To Call a Form When Form Name is a String Variable

    If you are going to use LaVolpe's code, make sure you set the RunReport public variable before calling any Form properties such as Caption.

    Calling/setting a Form's property (or any control on the Form) will fire the Form_Load event if the form is not yet loaded.

  10. #10

    Thread Starter
    New Member
    Join Date
    Sep 2009
    Posts
    11

    Re: How To Call a Form When Form Name is a String Variable

    Pradeep: Calling Form_Load twice won't work...but thanks for the suggestion.

    LaVolpe: I don't see how your code is different from my originally posted code. Bruce hit it on the head when he said that you have to set the public variable "RunReport" before setting the Form object b/c that kicks off Form_Load. This is a classic chicken/egg scenario b/c you can't set the form's property before you create the form object and once you create the form object it fires the Form_Load event.

    Normally, we use code such as this:
    Code:
    Dim oCaseReportsMenu As New Frm_Menu
    oCaseReportsMenu.RunReport = "Case Reports Menu"
    Load oCaseReportsMenu
    oCaseReportsMenu.Show
    to create a form object and pass the RunReport parmameter. In this case Form_Load won't fire until you call the Load command. The problem is that the form name (Form_Menu in this example) is in my database and gets retrieved into a string variable. If you know of a way to use this same type of code with the form name is a string variable, then we've got a solution. The ugly solution is to hard-code the form names and use a Case statement, but that is not good form and should be used as a last resort.

    Any ideas?

  11. #11
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: How To Call a Form When Form Name is a String Variable

    Quote Originally Posted by edperlstein View Post
    ...LaVolpe: I don't see how your code is different from my originally posted code
    That's one statement I always dislike reading. Shooting it down before you have even tried it. If you did try it, you will see that the form's Load event is not fired before you set the public variable -- which is what you wanted.

    Now I didn't inlcude the New keyword in the sample function, you'll want to add that. And if you did, your code would change slightly too:
    Code:
    Dim oCaseReportsMenu As Form
    Set oCaseRerportsMenu=LoadTheForm("Frm_Menu")
    oCaseReportsMenu.RunReport = "Case Reports Menu"
    Load oCaseReportsMenu
    oCaseReportsMenu.Show
    Quote Originally Posted by edperlstein
    ...If you know of a way to use this same type of code with the form name is a string variable, then we've got a solution. The ugly solution is to hard-code the form names and use a Case statement, but that is not good form and should be used as a last resort.
    Dynamcally loading the form is triggering the Load event before you want to. And if calling the Load event more than once (as suggested earlier) is an issue, and you don't want to modify the other forms to behave differently, then the ugly solution may be your best solution. I think you have all the possible choices.

    Edited: If you did modify your other forms, you might want to add the following to their Load events. You can then dynamically load the forms, your other Load event code won't run, set the RunReport variable, then call the Load event manually as suggested earlier.
    If RunReport = "" Then Exit Sub
    Last edited by LaVolpe; Sep 10th, 2009 at 02:08 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  12. #12

    Thread Starter
    New Member
    Join Date
    Sep 2009
    Posts
    11

    Re: How To Call a Form When Form Name is a String Variable

    LaVolpe: I apologize. I completely appreciate your suggestions and input. I will try your solution before commenting further. Thanks.

  13. #13
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: How To Call a Form When Form Name is a String Variable

    Quote Originally Posted by edperlstein View Post
    LaVolpe: I apologize. I completely appreciate your suggestions and input. I will try your solution before commenting further. Thanks.
    No biggie, you do have multiple solutions, each with their own pros/cons. I did modify/update the posted sample function to include the New keyword. Not all forms may need to be loaded as "New", tweak as needed.
    Last edited by LaVolpe; Sep 10th, 2009 at 02:17 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  14. #14
    PowerPoster
    Join Date
    Oct 2002
    Location
    British Columbia
    Posts
    9,758

    Re: How To Call a Form When Form Name is a String Variable

    The info here http://msdn.microsoft.com/en-us/libr...39(VS.60).aspx might help you out, especially the section Remaining Created, But Not Loaded

  15. #15

    Thread Starter
    New Member
    Join Date
    Sep 2009
    Posts
    11

    Re: How To Call a Form When Form Name is a String Variable

    LaVolpe: Thank you for your insight and expertise. Your example worked beautifully.

    Bruce: Thanks for the link to that article. That was really informative.

    Now on to the next hurdle. Using the same situation where I have the names stored in a database, rather than form names I will need to call functions. Does anyone know how I can call a Vb function when the name of the function is stored as a string? I realize that I could use the same Case structure from LaVolpe's example to hard-code the Function names, however those change more often than the Form names (and there are hundreds more). Any thoughts?

    Thanks

  16. #16
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: How To Call a Form When Form Name is a String Variable

    VB has built in support. But the function/sub must be PUBLIC. Use VB's CallByName.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  17. #17

    Thread Starter
    New Member
    Join Date
    Sep 2009
    Posts
    11

    Re: How To Call a Form When Form Name is a String Variable

    As far as I can tell, CallByName only works with a class object that allows Get, Let, Set or Method call types. I need to call a public function rather than an object. For instance:
    Code:
    Public Function CreateReport()
    ~~~ Creates a report ~~~
    End Function
    I don't understand how I can call this function using CallByName?

  18. #18
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: How To Call a Form When Form Name is a String Variable

    Quote Originally Posted by edperlstein
    As far as I can tell, CallByName only works with a class object that allows Get, Let, Set or Method call types
    VB forms are classes. Functions/Subs are methods and though not used often, forms can contain public get/let/set properties (though public variables are really properties as shown below).

    In a test project...
    1. Add Form2
    2. Copy & paste this to Form2
    Code:
    Option Explicit
    Public ReportName As String
    
    Private Sub Form_Load()
         Me.Caption = ReportName
    End Sub
    Public Sub TestSub(msgboxTitle As String)
       MsgBox msgboxTitle
    End Sub
    PUblic Function Add2Numbers(nr1 As Long, nr2 As Long) As Long
          Add2Numbers = nr1 + nr2
    End Function
    3. Add a command button to Form1
    Code:
    Private Sub Command1_Click()
        CallByName Form2, "TestSub", vbMethod, "Hello World"
        MsgBox "2000+9 = " & CallByName(Form2, "Add2Numbers", vbMethod, 2000, 9)
        CallByName Form2, "ReportName", VbLet, "Quarterly Earnings"
        Form2.Show ' notice the caption in Form2 ;)
    End Sub
    4. Run the test project

    Edited: It wasn't clear from your posting and I may have misunderstood/assumed incorrectly. These functions are in forms, correct? If not, then the above does not apply if the functions are in a module. CallByName does not work with modules.
    Last edited by LaVolpe; Sep 10th, 2009 at 07:39 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  19. #19

    Thread Starter
    New Member
    Join Date
    Sep 2009
    Posts
    11

    Re: How To Call a Form When Form Name is a String Variable

    Thanks for the explanation. The function is in a module. I could not find any information on CallByName that specifically stated that it wouldn't work with modules, so thank you for that info.

    Any idea on how I can call a function in a module if the function name is a string variable (other than using the Case statement and hard coding each function as a case)?

  20. #20
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: How To Call a Form When Form Name is a String Variable

    Others may have some ideas, I personally don't at this time -- never attempted it.

    1. Why it doesn't work with modules is simply because a module is not a class.
    2. A possible workaround is to store the functions in a class and expose the class as a public property in a module so all forms can access it.

    The setup is a bit awkward but will work. Example follows
    -- in new test project add 1 form, 1 module and 1 class. Name the class: clsFunctions
    In class copy & paste this
    Code:
    Option Explicit
    
    Public Sub TestSub(msgBoxTitle As String)
        MsgBox msgBoxTitle
    End Sub
    in module, copy and paste this
    Code:
    Option Explicit
    
    Private classFunctions As clsFunctions
    
    Public Property Get Functions() As clsFunctions
        If classFunctions Is Nothing Then Set classFunctions = New clsFunctions
        Set Functions = classFunctions
    End Property
    in form, add command button and copy & paste this. Then run project
    Code:
    Option Explicit
    
    Private Sub Command1_Click()
        CallByName Functions, "TestSub", VbMethod, "Hello World"
    End Sub
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  21. #21

    Thread Starter
    New Member
    Join Date
    Sep 2009
    Posts
    11

    Re: How To Call a Form When Form Name is a String Variable

    Thanks for the explanation and examples, LaVolpe. I'll have to store that away for another use. I have hundreds of functions in my modules, so moving them to class modules isn't an option.

  22. #22
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: How To Call a Form When Form Name is a String Variable

    Quote Originally Posted by edperlstein View Post
    Thanks for the explanation and examples, LaVolpe. I'll have to store that away for another use. I have hundreds of functions in my modules, so moving them to class modules isn't an option.
    Moving them is not an issue I would think: copy, cut & paste. You wouldn't be using classes (plural), you'd only be using one class, all functions in that class.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  23. #23

    Thread Starter
    New Member
    Join Date
    Sep 2009
    Posts
    11

    Re: How To Call a Form When Form Name is a String Variable

    What I meant is that:
    1) my IT department wouldn't go for it, and
    2) the end doesn't justify the means.

    But thank you...

    Any other ideas on how I can achieve my goal of calling a function in a module using a string variable that contains the function name is appreciated.

  24. #24
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: How To Call a Form When Form Name is a String Variable

    Well, if you app must use string names for the functions, your IT dept may have no choice other than maybe one of the following 2 options.

    1. Using Select Case statements may be doable but can be very difficult to maintain and set up. Notice that conversion to specific variable types for the parameters may be required.
    -- add 1 form with cmd button, and 1 module. Copy & paste
    Code:
    ' in the module:
    Option Explicit
    
    Public Function BASCallByName(FunctionName As String, ParamArray varArgs() As Variant) As Variant
    
        Select Case LCase$(FunctionName)
        Case "testsub"
            TestSub CStr(varArgs(0))
        Case "add2numbers"
            BASCallByName = Add2Numbers(CLng(varArgs(0)), CLng(varArgs(1)))
        End Select
    
    End Function
    
    ' the functions do not have to be public if they are in
    ' the same module as the BASCallByName function.
    ' Otherwise, they must be Public if in another module
    Private Sub TestSub(msgboxTitle As String)
       MsgBox msgboxTitle
    End Sub
    Private Function Add2Numbers(nr1 As Long, nr2 As Long) As Long
          Add2Numbers = nr1 + nr2
    End Function
    
    ' in the form:
    Private Sub Command1_Click()
        BASCallByName "TestSub", "Hello World"
        MsgBox "200+9 = " & BASCallByName("Add2Numbers", 2000, 9)
    End Sub

    2. VB allows the use of AddressOf for module functions. With this address you can actually call functions using CallWindowProc API. However, it does have limitations: function must have 4 parameters. There are hacks and workarounds that use Assembly to combat this limitation. But overall, this is a very complicated workaround and you'd still have to build a cross-reference of AddressOf pointers to function names.

    Edited: AddressOf pointers are not static. The can change each time your app runs.
    Last edited by LaVolpe; Sep 11th, 2009 at 02:19 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  25. #25

    Thread Starter
    New Member
    Join Date
    Sep 2009
    Posts
    11

    Re: How To Call a Form When Form Name is a String Variable

    Thanks, LaVolpe. Unless someone else has the magic answer, it looks like I may have to use hard-coded function calls inside Select Case statements.

    Is it possible that VB .NET has the ability to do what I need?

  26. #26
    Addicted Member ZenDisaster's Avatar
    Join Date
    Dec 2006
    Location
    Bay Area, CA
    Posts
    140

    Re: How To Call a Form When Form Name is a String Variable

    Your predicament reminds me of this post.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width