如何一次删除一个动态添加的用户窗体控件?

问题描述 投票:1回答:1

我正在构建一个锻炼日志记录应用程序,该应用程序允许用户在运行用户表单时添加动作,重复次数和相关的体重。 (您也可以将其视为“拣选订单”,例如“ 3”,“红色”,“铅笔”,“ 2”,“蓝色”,“标记”等))>

单击“ +”按钮后,代码将添加两个文本框和组合框。

单击“-”按钮时,只会删除最后添加的控件组,但是如果再次单击“-”按钮,则会收到“灾难性故障”错误消息。

我很确定需要使用controls.remove (object).name删除这些控件,但是一旦删除了最后一个组,则需要将对象变量更新为下一个我可能要删除的组。 >

我在这里找到了类似的问题并给出了答案,但这些问题删除了所有用户窗体控件。我只想删除最后添加的组。

enter image description here

Option Explicit
Public movementCounter As Integer
Public repsTextBox As Object
Public movementComboBox As Object
Public weightTextBox As Object
Public cntrlsColl As Collection

Private Sub addMvmtCmndButt_Click()

    movementCounter = movementCounter + 1

    Set repsTextBox = Controls.Add("Forms.TextBox.1")
    Set movementComboBox = Controls.Add("Forms.ComboBox.1")
    Set weightTextBox = Controls.Add("Forms.TextBox.1")

    With repsTextBox
        .Name = "RepsTextBox" & movementCounter
        .Height = 18
        .Width = 45
        .Left = 10
        .Top = 30 * (movementCounter - 1) + 5
    End With

    With movementComboBox
        .Name = "MovementComboBox" & movementCounter
        .Height = 18
        .Width = 90
        .Left = 65
        .Top = 30 * (movementCounter - 1) + 5
        .RowSource = listsSht.Range("movementList").Address
    End With

    With weightTextBox
        .Name = "WeightTextBox" & movementCounter
        .Height = 18
        .Width = 45
        .Left = 165
        .Top = 30 * (movementCounter - 1) + 5
    End With

End Sub

Private Sub deleteMvmtCmndButt_Click()

'Works, but only for the most recently added group of controls
    With Me.Controls
        .Remove repsTextBox.Name
        .Remove movementComboBox.Name
        .Remove weightTextBox.Name
    End With

'update what the next group of controls will be on-deck
'    If movementCounter > 0 Then
'        repsTextBox.Name = "RepsTextBox" & movementCounter
'        movementComboBox.Name = "MovementComboBox" & movementCounter
'        weightTextBox.Name = "WeightTextBox" & movementCounter
'    End If

End Sub

我正在构建一个锻炼日志记录应用程序,该应用程序允许用户在运行用户表单时添加动作,重复次数和相关的体重。 (您也可以将其视为“订单拣选” ...

excel vba userform
1个回答
0
投票

尝试以下代码...

Private Sub deleteMvmtCmndButt_Click()

    If movementCounter > 0 Then
        With Me.Controls
            .Remove "RepsTextBox" & movementCounter
            .Remove "MovementComboBox" & movementCounter
            .Remove "WeightTextBox" & movementCounter
        End With
        movementCounter = movementCounter - 1
    End If

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.