从用户窗体中删除动态添加的控件

Remove Dynamically Added Controls from Userform

我有一个 Excel 带有动态添加的复选框的用户表单。

我使用如下代码添加复选框:

Set chkBox = Me.Controls.Add("Forms.Checkbox.1", "Checkbox" & i)

我想删除所有这些复选框。

Dim j As Integer
'Remove all dynamically updated checkboxes
For Each cont In Me.Controls
    For j = 1 To NumControls
        If cont.Name = "Checkbox" & j Then
            Me.Controls.Remove ("Checkbox" & j)
        End If
    Next j
Next cont

我收到以下错误消息:

添加控件检查似乎可以解决此问题。不完全确定为什么,但它有效。

   Dim j As Integer
'Remove all dynamically updated checkboxes
For Each cont In Me.Controls
    If TypeName(cont) = "CheckBox" Then
        For j = 1 To NumControls
            If cont.Name = "Checkbox" & j Then
                Me.Controls.Remove cont.Name
                Exit For
            End If
        Next j
    End If
Next cont

假设没有其他控件名称以"Checkbox",

开头
For Each cont In Me.Controls
    If InStr(cont.Name, "Checkbox") = 1 Then
        Me.Controls.Remove cont.Name
    End If
Next cont

更好的方法可能是跟踪您创建的控件(例如在集合中),并使用它来删除它们。

这样您的代码就不会绑定到名称格式,也可以应用于其他控件类型。

Private cbxs As Collection

Private Sub UserForm_Initialize()
    Set cbxs = New Collection
End Sub

' Remove all dynamicly added Controls
Private Sub btnRemove_Click()
    Dim i As Long
    Do While cbxs.Count > 0
        Me.Controls.Remove cbxs.Item(1).Name
        cbxs.Remove 1
    Loop
End Sub


' Add some Controls, example for testing purposes
Private Sub btnAdd_Click()
    Dim i As Long
    Dim chkBox As Control
    For i = 1 To 10
        Set chkBox = Me.Controls.Add("Forms.CheckBox.1", "SomeRandomName" & i)
        chkBox.Top = 40 + i * 20
        chkBox.Left = 20
        cbxs.Add chkBox, chkBox.Name  '- populate tracking collection
    Next

    ' Demo that it works for other control types
    For i = 1 To 10
        Set chkBox = Me.Controls.Add("Forms.ListBox.1", "SomeOtherRandomName" & i)
        chkBox.Top = 40 + i * 20
        chkBox.Left = 60
        cbxs.Add chkBox, chkBox.Name
    Next

End Sub

如果您已经知道控件的名称、类型和数量,为什么要双循环?

请注意,只能删除在运行时创建的控件。

'the following removes all controls created at runtime
Dim i As Long
On Error Resume Next
With Me.Controls
    For i = .Count - 1 to 0 step -1
        .Remove i
    Next i
End With
Err.Clear: On Error GoTo 0

对于您的情况:'如果所有命名都正确

Dim j&
For j = 1 To NumControls
    Me.Controls.Remove "Checkbox" & j
Next j

我使用命令按钮重写了原始代码,只是添加了 "Me.Controls.Count" 而不是 "NumControls" 并将 "Cont" 定义为控件。它似乎对我有用。如果这对您有用,请告诉我:

-->

On Error Resume Next
Dim Cont As Control
Dim C As Integer
'Remove all dynamically updated checkboxes
For Each Cont In Me.Controls
    For C = 1 To Me.Controls.Count
    If Cont.Name = "CommandButton" & C Then
        Me.Controls.Remove ("CommandButton" & C)
    End If
    Next C
Next Cont

另一种 select 保留哪些控件和删除哪些控件的方法是使用 .Tag 属性。 这允许在添加控件时对其进行一些精细控制,例如通过使用 .Tag 作为位域。

创建时间:

With Me.Controls.add("Forms.Label.1", Visible:=True)
{code}
    .Tag = 1
{more code}

然后到了收拾的时候:

For Each C In Me.Controls
    If C.Tag = 1 Then Me.Controls.Remove C.Name
Next