当用户按以下顺序激活时,我想在运行时添加动态用户窗体控件,例如(标签,文本框)。
我想要以下内容
当userfrom激活时,需要询问用户字段数,他/她想插入? 如果用户回答7,则需要按以下顺序添加字段“ 3列顺序”
标签1文本框1标签2文本框1标签3文本框3
标签4文本框4标签5文本框5标签6文本框6
Label7 textbox7 ........依现场用户数量而定 问。
请求增强代码:
我尝试了以下代码:
Private Sub UserForm_Initialize()
Dim i As Long
number = 10 'InputBox("Enter no of text-boxes and labels you wish to create at run-time", "Enter TextBox & Label Number")
Dim txtB1 As control
For i = 1 To 5
Set txtB1 = Controls.Add("Forms.TextBox.1")
With txtB1
.Name = "txtBox" & i
.Height = 20
.Width = 50
.Left = 70
.Top = 20 * i * 1
End With
Next i
For i = 6 To 10
Set txtB1 = Controls.Add("Forms.TextBox.1")
With txtB1
.Name = "txtBox" & i
.Height = 20
.Width = 50
.Left = 200
.Top = 20 * i - 100 * 1
End With
Next i
Dim lblL1 As control
For i = 1 To 5
Set lblL1 = Controls.Add("Forms.Label.1")
With lblL1
.Caption = "Label" & i
.Name = "lbl" & i
.Height = 20
.Width = 50
.Left = 20
.Top = 20 * i * 1
End With
Next i
For i = 6 To 10
Set lblL1 = Controls.Add("Forms.Label.1")
With lblL1
.Caption = "Label" & i
.Name = "lbl" & i
.Height = 20
.Width = 50
.Left = 150
.Top = 20 * i - 100 * 1
End With
Next i
Dim q As Long
For q = 1 To 5
Controls("lbl" & q) = Cells(1, q)
Next q
For q = 6 To 10
Controls("lbl" & q) = Cells(1, q)
Next q
End Sub
答案 0 :(得分:1)
这是在3列中进行无限数量控件的一种方法。代替使用嵌套的For循环,请尝试使用Do循环:
Option Explicit
Private Sub UserForm_Initialize()
Dim nof As Integer
nof = InputBox("Enter no of text-boxes and labels you wish to create at run-time", "Enter TextBox & Label Number")
Dim nob As Integer
nob = InputBox("Enter no of blanks you wish to create at run-time", "Enter Blanks")
CreateFields nof, nob
End Sub
Private Sub CreateFields(ByVal NumberOfFields As Integer, _
ByVal NumberOfBlankFields As Integer)
Dim i As Integer
Dim j As Integer
Dim Top As Single
Dim Left As Single
Top = 20
Left = 20
i = 1
j = 1
Do While i <= NumberOfFields + NumberOfBlankFields
If i > NumberOfBlankFields Then
CreateLabel "lbl" & j, "Label" & j, Top, Left
CreateTextBox "txtBox" & j, "Text" & j, Top, Left + 30
j = j + 1
End If
i = i + 1
If i Mod 3 = 1 Then
Top = Top + 50
Left = 20
Else
Left = Left + 100
End If
Loop
End Sub
Private Sub CreateLabel(ByVal Name As String, _
ByVal Caption As String, _
ByVal Top As Single, _
ByVal Left As Single)
With Controls.Add("Forms.Label.1")
.Name = Name
.Caption = Caption
.Height = 20
.Width = 50
.Left = Left
.Top = Top
End With
End Sub
Private Sub CreateTextBox(ByVal Name As String, _
ByVal Text As String, _
ByVal Top As Single, _
ByVal Left As Single)
With Controls.Add("Forms.TextBox.1")
.Name = Name
.Text = Text
.Height = 20
.Width = 50
.Left = Left
.Top = Top
End With
End Sub
当然,您可以根据需要调整控件的间距。