一组动态文本框

时间:2013-04-03 19:33:07

标签: arrays dynamic excel-vba textbox vba

在表单中,每次单击te按钮时,都必须出现一个新文本框。 我想用所有这些文本框制作一个数组。 问题是,这些文本框具有动态名称。 我如何将它们放入数组中? 这是我的代码:

Set nieuwtxtingredient = Me.Controls.Add("Forms.Textbox.1", "Ingredient", True)
With nieuwtxtingredient
.Width = Me.txtIngredient0.Width
.Height = Me.txtIngredient0.Height
.Left = Me.txtIngredient0.Left
.Top = Me.txtIngredient0.Top + 30 * aantalBoxes
.Name = "txtIngredient" + CStr(aantalBoxes)
End With

Dim naam As String
Dim ingredientArray() As String

ReDim ingredientArray(1 To aantalBoxes)
ingredientArray(aantalBoxes) = **Me.txtIngredient0.Value**

2 个答案:

答案 0 :(得分:0)

在您的代码中,您可以在nieuwtxtingredient中保存对新文本框的引用。

您可以将此引用保存在Textbox数组中,然后读取每个引用的名称和值。

我建议您修改代码:

Dim aantalBoxes As Integer
Dim ingredientArray() As Control

 Private Sub btnVoegToe_Click()

    Dim aantalRecepten As Integer
    Dim Teller As Integer

    aantalRecepten = Cells(2, Columns.Count).End(xlToLeft).Column

    Cells(2, aantalRecepten + 2).Value = Me.txtNaamRecept.Value

    For Teller = 1 To aantalBoxes ' <-- starts at 1, formula below adjusted

        Cells(2 + Teller, aantalRecepten + 2).Value = ingredientArray(aantalBoxes).Value

    Next Teller

End Sub

Private Sub btnVolgendeIngredient_Click()

    aantalBoxes=aantalBoxes + 1     ' <-- must calculate the total

    ReDim Preserve ingredientArray(aantalBoxes) ' <-- you had this in the earlier version

    Set nieuwtxtingredient = Me.Controls.Add("Forms.Textbox.1", "Ingredient", True)

    With nieuwtxtingredient

        .Width = Me.txtIngredient0.Width
        .Height = Me.txtIngredient0.Height
        .Left = Me.txtIngredient0.Left
        .Top = Me.txtIngredient0.Top + 30 * aantalBoxes
        .Name = "txtIngredient" + CStr(aantalBoxes)

    End With
                                       ' first Textbox is numbered 1
    set ingredientArray(aantalBoxes) = nieuwtxtingredient  ' <-- you had this in the earlier version

End Sub

答案 1 :(得分:0)

请参阅此示例http://jsfiddle.net/7zkzttpr/2/

$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});   

当您创建新文本框时,请为文本框指定与数组相同的名称,以便您可以获取数组中所有文本框的值。