• Using VBA to add controls (programmatically) (VBA for Word 2000)

    Home » Forums » AskWoody support » Productivity software by function » Visual Basic for Applications » Using VBA to add controls (programmatically) (VBA for Word 2000)

    Author
    Topic
    #363021

    I have a “For each …” that I need to add controls for as follows:

    Issue 1:
    For each item that matches the criteria, I need to add two labels that match two variables that would have been set. I know (generically) how to set the caption once they are there, but am not sure how to have VBA create the labels.

    Issue 2:
    For each item that matches the criteria, I need to add a couple of combo boxes. The values in the combo boxes will be the same for each item.

    To sum, for each item that matches the criteria I need to create the following row of controls on my form:

    Label1 Label2 Combo1 Combo2

    (Obviously each label and combo box would have to have diffferent names for each row).

    Thanks for your help!!
    Troy

    Viewing 1 reply thread
    Author
    Replies
    • #552738

      Hi Troy,

      I think that the Controls collection of the UserForm is what you need. Here is an example that uses a command button to add a new label, named lblPhoneNumber, making it visible, then setting the appropriate properties:

      Dim DesiredControl As Control
      Private Sub cmdAddControls_Click()

      Set DesiredControl = Controls.Add(“Forms.Label.1”, lblPhoneNumber, Visible)
      DesiredControl.Left = 18
      DesiredControl.Top = 100
      DesiredControl.Width = 175
      DesiredControl.Height = 20
      DesiredControl.Caption = “Phone No.”

      End Sub

      To add a combobox the first parameter to the add method would be “Forms.Combobox.1”. You can find more details in the Help topic of “Controls Collection”. Have fun!

    • #552739

      Hi again Troy,

      One more thing that might help. Use the Controls.Add method to create and position the controls but don’t try to add the items to the combobox right then and there. You can handle populating both comboboxes with the same data in the UserForm’s AddControl event which will fire after each control is added. If the type of control just added is a combobox just fill it with the values needed.

      Private Sub UserForm_AddControl(ByVal Control As MSForms.Control)
      If TypeOf Control Is ComboBox Then
      Control.AddItem “Lounge”
      Control.AddItem “Lex”
      Control.AddItem “Lizard”

      End If

      End Sub

    Viewing 1 reply thread
    Reply To: Reply #552738 in Using VBA to add controls (programmatically) (VBA for Word 2000)

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information:




    Cancel