在VBA中填充TextBox

时间:2016-09-10 11:43:03

标签: vba excel-vba excel

我正在使用表单来展示出色的工作。代码根据工作表调用“Jobcardslive”上使用的行数创建了许多文本框

我可以在表单上创建正确数量的文本框但我还想用文件框填充存储在行A中的值

例如,如果我在工作表上填充了4行,它将创建4个名为vehicle1 - 4等的文本框 我还希望它能够在工作表中使用A1填充vehicle1,使用A2等填充vehicle2

盒子创造得很好 我目前使用的代码是

Dim txtB1 As Control
Dim TextBox_Name As String
Dim f As String
f = ThisWorkbook.Sheets("Jobcardslive").Range("A" & Rows.Count).End(xlUp).Row - 1
Dim i

For i = 0 To f
    Set txtB1 = Controls.Add("Forms.TextBox.1")
    With txtB1
        .Name = "vehicle" & i
        .Height = 20
        .Width = 200
        .Left = 10
        .Top = 10 * i * 2
    End With
Next i

非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

你可以如下:

    Dim txtB1 As MSForms.TextBox '<--| declare it as a TextBox instead of Control, to have Intellisense show you real `Textbox` object specific members
    Dim i As Long

    With ThisWorkbook.Sheets("Jobcardslive")
        For i = 1 To .Range("A" & .Rows.Count).End(xlUp).Row
            Set txtB1 = Me.Controls.Add("Forms.TextBox.1")
            SetTextBox txtB1, i, Range("A" & i).value
        Next i
    End With

因此还要求以下特定Sub SetTextBox正确初始化文本框的任务:

Sub SetTextBox(txtB As MSForms.TextBox, i As Long, v As Variant)
    With txtB
        .name = "vehicle" & i
        .height = 20
        .Width = 200
        .Left = 10
        .Top = 10 * i * 2
        .value = v
    End With
End Sub