如何在运行时动态创建控件 [英] How to create controls dynamically at runtime

查看:60
本文介绍了如何在运行时动态创建控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据要查看的特定工作表上的列数在excel用户窗体中创建可变数量的控件(组合框).理想情况下,我想在运行时删除现有的并创建新的,而不是创建100个左右,而只是在可见和不可见之间来回切换.我现在所拥有的将创建一个组合框和循环,但它只会创建1.看起来好像该组合框被覆盖了,并以创建的最后一个组合框结束.有什么建议可以在运行时将所有内容都添加到相同的用户表单中?

I am trying to create a variable number of controls (combo boxes) in an excel userform based on the number of columns that are on a particular worksheet being viewed. Ideally I would like to delete and existing ones and create new ones at run-time, rather than creating 100 or so and just toggling back and forth between visible and invisible. What I have at the moment will create a combo box and loop, but it only creates 1. It looks as though the combo box is being overwritten and ends with the last combo box created. Any suggestions to get all onto the same userform at run-time?

Private Sub CommandButton1_Click()
 Dim cCont As New Control

 Dim ws As Worksheet
 Dim lc As Long
 Dim i As Long

 Set ws = Loan_Data

 lc = Loan_Data.Cells(1, Columns.Count).End(xlToLeft).Column


 For i = 1 To lc
    Set cCont = Me.Controls.Add("Forms.CommandButton.1", "NewCombo" & i)
    With cCont
        .Caption = cCont.Name
        .AutoSize = True
        .Visible = True
    End With
 Next i

结束子

推荐答案

我可以与您分享一个我在运行时用于创建一些ComboBox的过程的示例.

I can share with you an example of a Procedure I used to create some ComboBoxes at Run time.

Private Sub Agrega_Combo(Unidades As Integer)
'Procedimiento para agregar los ComboBox, etiquetas y unidades a la lista.
    Dim i, j As Integer
    Dim Cmb As Control
    Dim Lbl As Control

    'Ciclo para crear los ComboBox y Etiquetas en el 'ArrUnidades'
    For i = 1 To UBound(ArrUnidades)
    'Agrega el ComboBox
        Set Cmb = Me.Controls.Add("Forms.combobox.1")
        'Se establece el nombre y la posición del nuevo ComboBox
        With Cmb
            .Name = "Combobox" & i
            .Left = 66
            .Width = 36
            If i = 1 Then
                .Top = 34
            Else
                .Top = 34 + (24 * (i - 1))
            End If
        End With
    'Agrega la Etiqueta'
        Set Lbl = Me.Controls.Add("Forms.label.1")
        With Lbl
            .Name = "Label" & i
            .Caption = ArrUnidades(i) & " :"
            .Left = 30
            .Width = 36
            If i = 1 Then
                .Top = 38
            Else
                .Top = 38 + (24 * (i - 1))
            End If
        End With
        'Ciclo para agregar las unidades indicadas al llamar el procedimiento.
        For j = 1 To Unidades
            Me.Controls("ComboBox" & i).AddItem j
        Next j
        'Selecciona el primer valor de la lista.
        Me.Controls("ComboBox" & i).Text = Me.Controls("ComboBox" & i).List(0)
    Next i
End Sub

希望有帮助.

这篇关于如何在运行时动态创建控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆