Creating Forms and Objects in Code

Just a quickie, I'm trying to Automate a system we have here and to do it more efficiently I want to write an app to basically create forms and objects for me so that they can be saved. I'm sure I can create it by writing to a text file and saving it, is there another way of doing it other than this and still be able to save the forms for later use.

Who is Participating?
This is how to create a form bases on another one and put some labels on it:

Private Sub Command1_Click()
Dim frm As Form1
Dim ctl As Control
Dim lX As Long
Dim lY As Long
Dim lInc As Long
Dim i As Integer

    lInc = 200
    'create 10 labels
    Set frm = New Form1
    With frm
        For i = 1 To 10
            Set ctl = .Controls.Add("VB.Label", "Label" & CStr(i))
            ctl.Top = lY
            ctl.Left = lX
            ctl.Caption = "This is label #" & CStr(i)
            ctl.AutoSize = True
            ctl.Visible = True
            lY = lY + lInc
        Next i
    End With
    frm.Show vbModal
    Set frm = Nothing

End Sub

I don't think it is possible to save the new form. Maybe if you make an application in the VB-IDE ?

Why don't you just generate it dynamic every time ? This way the data is also always actual !

Try this

Private Sub Command1_Click()
Dim cnf As New Form1
With cnf
.Height = 1000
.Width = 2000
.Caption = "new form"
End With
cnf.Visible = True
End Sub
wolfjjjAuthor Commented:
But I dont just want them created once, I want to be able to save them. Basically I want to have a table of data, basically questions (labels) and answers (checkboxes, textfields, options, lists and combo boxes) and be able to loop through and create a form based on those questions and answers and be able to save the form, so basically its an automated way of creating an application, so you only need to rearrange the objects to the places you want them to be.
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Sorry,had the question open for a while....
wolfjjjAuthor Commented:
Well because as I said before I want to AUTOMATE the process of creating the applications, that why I want to save them and no matter how much time u spend on creating the form dynamically they will still have to move stuff around and get it into the right positions and that kinda stuff.
wolfjjjAuthor Commented:
OK here's an example of what I would be doing, we might have a questionaire with say 50 questions, rather than messing around setting up a form with 50 lots of checkboxes, comboboxes or options I'd much rather just type in the questions and have a program design it for me and I can just neaten thing up after its created everything, make sense? And it's not going to be just a once off kinda thing, it's something that would be used on a daily basis to create different forms.
So are you wanting to store the form info generated from the questions and store it in a text file, so you can recall it and create an object (form) with it, to use again?
Why don't you save a form in the ide... then generate the questions and buttons, labels , text boxes at run time?
wolfjjjAuthor Commented:
Because ideally I'm going to create code to go behind the buttons and checks aswell as just creating them. All I really want is to have it setup a basic design so I can just move things around and make it look nice and then add some functionality to it without having to spend hours designing the thing from scratch. Also each one is going to be used by large numbers of people and setuping up on runtime could get very messy.
I don't think so since it just repeats what is said here: the recreation of a form, is this PAQ as an array.

If I'm right, wolfjjj, your main problem is how to save it ?

Valliappan ANSenior Tech ConsultantCommented:
Hi, Hope you got it. Look at these links for dynamic creation of controls to a form, from VB.
(An example, for what you are trying to do)
(For your reference - HOWTO: Create a Basic Add-in Using VB5 or VB6)

wolfjjjAuthor Commented:
Yer thats the prob, OK I've found one way of doing it using the CreateControl function here's some code if just chucked together trying to use it

Private Sub Command0_Click()
    Dim frm As Form
    Dim ctlLabel As Control, ctlText As Control
    Dim intDataX As Integer, intDataY As Integer
    Dim intLabelX As Integer, intLabelY As Integer
    Set frm = CreateForm(, "Template")
    intLabelX = 100
    intLabelY = 100
    intDataX = 1000
    intDataY = 100
    For I = 1 To 10
        Set ctlText = CreateControl(frm.Name, acTextBox, , "", "", intDataX, intDataY)
        Set ctlLabel = CreateControl(frm.Name, acLabel, , ctlText.Name, "NewLabel" & I, intLabelX, intLabelY)
        intLabelY = intLabelY + 500
        intDataY = intDataY + 500
        Set ctlText = Nothing
        Set ctlLabel = Nothing
    Next I
End Sub

I'm just using it through Access and VBA at the moment cos the apps can be done in either VB or Access VBA it doesnt really matter. But I'm still having probs getting it to do what I want it to do. It work when u create a new form but I cant get it to make changes to a form that already exists.
Ok, looked it up in MSDN:

It is possible to save a form in the IDE: Create an AddIn, make a public function and call it from your code.

Then in the code add this line:


You must add Form1 as a template to your addin and save it (in this case) in c:\temp.

Good luck!

Nitin SontakkeDeveloperCommented:
I am new on this thread, but i think this is something we have done 2-3 years ago. This is basically writing some of the VB yourself. But it's worth it for the functionality you want to provide. The very simple process is as follows and you make it as complex as your case is:

Forms table:

Form Id, Form Height, Width, Caption, and every other required property of respective data-type.

Controls table:

Form Id, Control Id, Control Type, Height, Width, MaxLength, Value, and again every other required property of respective data-type.

In VB.

Have a temp form which has an instance of EACH AND EVERY required control, .Visible = False.

Query db for forms table.

Do while Not rsForms.EOF
   Dim newForm as new tempForm
   'Set form properties here...
   'Query controls table here...
   'strQuery = "Select * from Controls where FormId = " & rsForms("FormId")
   Do while Not rsControls.EOF
      Select Case rsControls.ControlType
         Case 1 'Text box
            'instantiate from dummy control
            'and set properties from rsControls("MaxLength"), etc.
         'Take care of each control.
      End Select
   Set newForm = Nothing

Needless to say, you have write a routine to save any modifications (add/modify/delete) done by user back to db.

Please tell me if i am in line with what u are attempting.
wolfjjjAuthor Commented:
Yep thats exactly along the lines of what I'm trying to do but I want to be able to save the form once it's done as a .frm
Valliappan ANSenior Tech ConsultantCommented:
Did you look at my 2nd link and/or 1st link, it can be changed to create a form in design time with any number of controls you wish to, and from a database if need be.

You need to save the created form in design time, thats it. You create an add-in for your project in VB.

Hope that would solve your problem and if you wish to I can try to expand on it, as you give your exact requirement details. Or you can mail your form or data.
Nitin SontakkeDeveloperCommented:
As i perceive it, you want to do it as an application and not in IDE. Please correct me if i am wrong.

And if it is so, i am still not clear why you need it as a .frm file. Forgive me for my language.

Whether it is for developer or user, it is always a good idea to persist the information either in db or in .frm file but not in both. It is going to be a maintainance nightmare. I hope you see what i mean.

.frm is nothing but a properties persistance storage medium used by VB. We are using db instead.

>Basically I want to have a table of data, basically questions (labels) and answers (checkboxes, textfields, options, lists and combo boxes)<

If you have enough questions to make this approach viable, you should consider *not* hard coding them in the form.  Create some rules for the display of your questions based on information loaded from a database; display the appropriate controls based on fields in the record and initialize those controls with more data from the db.  Standardizing the layout for controls on those questions will only help the usability of your application.  You can make your app wizard style so that it shows a page of questions at a time, then when the next button is clicked load the next page of questions.  You have the advantage
of reusing the form over and over instead of having a new one for every page of questions.  For the controls, use control arrays and load the controls you need at runtime.

This system is more flexible and creates more reuse than the one you propose.
wolfjjjAuthor Commented:
Basically I suppose I'm designing a wizard to create the basics of the system for me. Does that make any more sense? It's only going to be used by the developers but what is produced will be saved and the end product will be used by the users.
Nitin SontakkeDeveloperCommented:
I am with u.

The only thing that comes to mind with the new input is (a bit horrible, but) as follows:

Study the structure the .frm file and write one with simple text io using VB such as...

Dim intHandle as Integer
intHandle = FreeFile
Open "filename" for output as intHandle
Print #intHandle, "Begin VB.Form frmTempForm"
Close #intHandle

As i guess, most of the contents of the .frm file will be routine. Use the .frm file of the temp form mentioned above.

Honestly, i am not very happy suggesting u this solution, but that's what u seem to be looking for, unfortunately.

Get back if i am unclear.
Hello wolfiii !
My suggestion:

1. Store all the Names,Indexes and types of the controls belonging top the form (you want to save) in a text file or use the frm-file itself.
2. Save the properties of the controls in the same Syntax as you would set them in vb eg: "frmTest.left=2001" or use or use the frm-file itself.
3. Create an app that reads the text file (*.frm) and generates the saved controls (in runtime of course)
4. Set the properties of the controls
a. if you use the frm-file you have to write your own routine (with CallByName)
b. if you use the syntax in 2. you can use this procedure

Sub DoWithObject(Anweisung As String)
    Dim Obj As Object
    Dim OB() As Teil
    Dim Index As Long
    Dim KlammerAuf As Long
    Dim KlammerZu As Long
    Dim PosPunkt_Alt As Long
    Dim PosPunkt_Neu As Long
    Dim Property As String
    Dim ValString As String
    Dim ValNumber As Long
    Dim ValBool As Boolean
    Dim ValType As Integer
    ReDim OB(0)
    PosPunkt_Neu = InStr(1, Anweisung, ".")
    Do While PosPunkt_Neu > 0
        Index = Index + 1
        ReDim Preserve OB(Index)
        OB(Index).Name = Mid(Anweisung, PosPunkt_Alt + 1, PosPunkt_Neu - PosPunkt_Alt - 1)
        KlammerAuf = InStr(1, OB(Index).Name, "(")
        KlammerZu = InStr(1, OB(Index).Name, ")")
        If KlammerZu > KlammerAuf + 1 Then
            OB(Index).Index = Val(Mid(OB(Index).Name, KlammerAuf + 1, KlammerZu - KlammerAuf - 1))
            OB(Index).Name = Mid(OB(Index).Name, 1, KlammerAuf - 1)
            OB(Index).Index = -1
        End If

        PosPunkt_Alt = PosPunkt_Neu
        PosPunkt_Neu = InStr(PosPunkt_Alt + 1, Anweisung, ".")
    PosPunkt_Neu = InStr(PosPunkt_Alt + 1, Anweisung, "=")
    If PosPunkt_Neu > PosPunkt_Alt + 1 Then
        Property = Trim(Mid(Anweisung, PosPunkt_Alt + 1, PosPunkt_Neu - PosPunkt_Alt - 1))
            ValString = Trim(Mid(Anweisung, PosPunkt_Neu + 1))
        End If
        Select Case True
            Case IsNumeric(ValString)
                ValType = 1
                ValNumber = Val(ValString)
            Case GetBool(ValString, ValBool)
                ValType = 2
            Case Else
                ValType = 3
        End Select
        On Error Resume Next
        If UBound(OB) > 0 Then
            Set Obj = Nothing
            Select Case LCase(Trim(OB(1).Name))
                Case "app"
                    Set Obj = App
                Case "clipboard"
                    Set Obj = Clipboard
                Case "forms"
                    If OB(1).Index >= 0 Then
                        Set Obj = Forms(OB(1).Index)
                        Set Obj = Forms
                    End If
                Case "licenses"
                    If OB(1).Index >= 0 Then
                        Set Obj = Licenses(OB(1).Index)
                        Set Obj = Licenses
                    End If
                Case "printer"
                    Set Obj = Printer
                Case "printers"
                    If OB(1).Index >= 0 Then
                        Set Obj = Printers(OB(1).Index)
                        Set Obj = Printers
                    End If
                Case "screen"
                    Set Obj = Screen
                Case "me"
                    Set Obj = Screen.ActiveForm
                Case Else
                    Dim FRM As Form
                    For Each FRM In Forms
                        If LCase(Trim(FRM.Name)) = LCase(Trim(OB(1).Name)) Then
                            Set Obj = FRM
                            Exit For
                        End If
                    Next FRM
            End Select
            If Not Obj Is Nothing Then
                For Index = 2 To UBound(OB)
                    If OB(Index).Index >= 0 Then
                        Set Obj = CallByName(Obj, OB(Index).Name, VbGet)(OB(Index).Index)
                        Set Obj = CallByName(Obj, OB(Index).Name, VbGet)
                    End If
                CallByName Obj, Property, VbLet, Choose(ValType, ValNumber, ValBool, ValString)
            End If
        End If
    End Sub
Sorry there is a missing function:

Function GetBool(Text As String, Optional ValueBool As Boolean, Optional ValueTxt As String) As Boolean
    Select Case LCase(Trim(Text))
        Case "wahr", "true", "ja", LCase(CStr(True))
            GetBool = True
            ValueBool = True
            ValueTxt = CStr(True)
        Case "falsch", "false", "nein", LCase(CStr(False))
            GetBool = True
            ValueBool = False
            ValueTxt = CStr(False)
        Case Else
            If IsNumeric(Trim(Text)) Then
                GetBool = True
                ValueBool = CBool(Trim(Text))
                ValueTxt = CStr(ValueBool)
                GetBool = False
                ValueTxt = ""
            End If
    End Select
End Function
ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101 or Netminder will return to finalize these if still open in seven days.  Please post closing recommendations before that time.

Question(s) below appears to have been abandoned. Your options are:
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> You cannot delete a question with comments, special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
Please click the Help Desk link on the left for Member Guidelines, Member Agreement and the Question/Answer process for further information, if needed.

Click you Member Profile to view your question history and keep them all current with updates as the collaboration effort continues, to track all your open and locked questions at this site.  If you are an EE Pro user, use the Power Search option to find them.  Anytime you have questions which are LOCKED with a Proposed Answer but does not serve your needs, please reject it and add comments as to why.  In addition, when you do grade the question, if the grade is less than an A, please add a comment as to why.  This helps all involved, as well as future persons who may access this item in the future to seek help.

To view your open questions, please click the following link(s) and keep them all current with updates.

------------>  EXPERTS:  Please leave any comments regarding your closing recommendations if this item remains inactive another seven (7) days.  Also, if you are interested in the cleanup effort, please click this link

Moderators will finalize this question if still open in 7 days, by either moving this to the PAQ (Previously Asked Questions) at zero points, deleting it or awarding expert(s) when recommendations are made, or an independent determination can be made.  Expert input is always appreciated to determine the fair outcome.
Thank you everyone.
Moderator @ Experts Exchange

P.S.  For any year 2000 questions, special attention is needed to ensure the first correct response is awarded, since they are not in the comment date order, but rather in Member ID order.
Hi wolfjjj,
It appears that you have forgotten this question. I will ask Community Support to close it unless you finalize it within 7 days. I will ask a Community Support Moderator to:

    Accept roverm's comment(s) as an answer.
    *** I really don't know, but the add-in idea sounds good.  PLEASE COMMENT if I'm wrong.

wolfjjj, if you think your question was not answered at all or if you need help, just post a new comment here; Community Support will help you.  DO NOT accept this comment as an answer.

EXPERTS: If you disagree with that recommendation, please post an explanatory comment.
DanRollins -- EE database cleanup volunteer
Valliappan ANSenior Tech ConsultantCommented:
Hope my comment could well be considered an answer.
hi valli_an,
I have examined the links that you provided and I have read and re-read this question several times.  The links that you provided did NOT show how to automate the process of generating VB source code files; nor did they provide any other technique to automate VB form generation.  That is the question that wolfjjj is asking.
EXPERTS: I am listening for additional comments.

-- Dan
Valliappan ANSenior Tech ConsultantCommented:
Thanks for your comments. I thought my 1st link, ameba states of creating an addin to automate the process of a number of controls, and also in the 2nd link, a similar add-in creation is mentioned. The 3rd link seems to be defining how to create a add-in. Hope the links give a hint on developing the add-in to create more controls in design time by automating the process.

Thanks for your time.
Per recommendation, force-accepted.

CS Moderator
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.