我正在使用VBA为Excel文件编写应用程序代码。简而言之,我需要根据ArrayList中某个变量的位置来更改我的文本框的名称。
我有一个文本框可以启动,当有人按下按钮时,它应该在第一个文本框后面添加一个文本框,并按下按钮多次执行此操作。因此,第一个框应命名为tbx1
,第二个框应命名为tbx2
,第三个框应命名为tbx3
,依此类推。
现在,当他们按下任何一个方框旁边的另一个按钮时,它会删除该框和按钮,并且在那个框之后的所有框都被命名为一个较低的按钮以弥补它。
任何想法如何做到这一点?我只是假设ArrayList是最好的策略,如果有更好的方法,请纠正我。
答案 0 :(得分:0)
以下是您可以根据自己的需求进行修改的示例。我有一个名为UClassList的用户窗体,带有一个命令按钮,cmdAdd和一个文本框tbxClass_1。
Private mEventButtons As Collection
Public Property Get ClassMax() As Long
ClassMax = 75
End Property
Private Sub cmdAdd_Click()
Dim i As Long
For i = 2 To Me.ClassMax
'find the first invisible control and make it visible
If Not Me.Controls("tbxClass_" & i).Visible Then
Me.Controls("tbxClass_" & i).Visible = True
Me.Controls("cmdClass_" & i).Visible = True
Exit For 'stop after one
End If
Next i
End Sub
Private Sub UserForm_Initialize()
Dim i As Long
Dim tbx As MSForms.TextBox
Dim cmd As MSForms.CommandButton
Dim clsEventClass As CEventClass
Set mEventButtons = New Collection
'Add as many textboxes and commandbuttons as you need
'or you can do this part at design time
For i = 2 To Me.ClassMax
Set tbx = Me.Controls.Add("Forms.TextBox.1", "tbxClass_" & i, False)
tbx.Top = Me.tbxClass_1.Top + ((i - 1) * 25) 'use the first textbox as the anchor
tbx.Left = Me.tbxClass_1.Left
tbx.Width = Me.tbxClass_1.Width
tbx.Height = Me.tbxClass_1.Height
'Create a delete commandbutton
Set cmd = Me.Controls.Add("Forms.CommandButton.1", "cmdClass_" & i, False)
cmd.Top = tbx.Top
cmd.Left = tbx.Left + tbx.Width + 10
cmd.Width = 20
cmd.Height = tbx.Height
cmd.Caption = "X"
'add delete commandbutton to the event class so they all share
'the same click event code
Set clsEventClass = New CEventClass
Set clsEventClass.cmdEvent = cmd
mEventButtons.Add clsEventClass
Next i
End Sub
我有一个名为CEventClass的自定义类。
Public WithEvents cmdEvent As MSForms.CommandButton
Private Sub cmdEvent_Click()
Dim i As Long
Dim lThisIndex As Long
Dim tbxThis As MSForms.TextBox
Dim tbxPrev As MSForms.TextBox
Dim uf As UClassList
Set uf = cmdEvent.Parent
'get the number that was clicked
lThisIndex = Val(Split(cmdEvent.Name, "_")(1))
'loop from the next textbox to the end
For i = lThisIndex + 1 To uf.ClassMax
Set tbxThis = uf.Controls("tbxClass_" & i)
Set tbxPrev = uf.Controls("tbxClass_" & i - 1)
'if it's not visible, clear and hide
'the previous textbox
If Not tbxThis.Visible Then
tbxPrev.Text = vbNullString
tbxPrev.Visible = False
uf.Controls("cmdClass_" & i - 1).Visible = False
Else
'if it's visible, copy it's text to the one above
tbxPrev.Text = tbxThis.Text
End If
Next i
End Sub
我没有添加,删除和跟踪一堆文本框,而是在启动(或设计时)创建全部75(或更少)。然后我根据需要制作然后隐藏它们。
您可以在此处查看我执行此操作的工作簿http://dailydoseofexcel.com/excel/ControlEventClass.xlsm