2014-09-24 86 views
0

我有一个用户窗体有一个文本框,并将任何值放入文本框将决定添加到用户窗体的动态控件的数量,然后有一个按钮,一旦点击我想要动态控件完全从用户窗体中删除。删除在运行时添加的控件

下面显示了用于创建动态控件的代码,该代码工作完全

For i = 1 To TextBox1.Value 
     newPosition = 360 

     Set cLabel = Me.Controls.Add("Forms.Label.1") 
      With cLabel 
       .Caption = "Label " & (i) 
       .Font.Size = 8 
       .Font.Bold = True 
       .Font.Name = "Tahoma" 
       '.Left = 70 
       .Left = 36 
       .Top = switchBoardLevel 
       .Width = 130 
      End With 


     switchBoardLevel = switchBoardLevel + newPosition   


     Set cButton = Me.Controls.Add("Forms.CommandButton.1") 
     With cButton 
      .Name = "CommandButton" & i 
      .Caption = "Calculate" 
      .Left = 300 
      .Top = buttonStartPosition 
      .Width = 45 
      .Height = 18 
     End With 

     ReDim Preserve TextListBox(1 To i) 
     Set TextListBox(i).ButtonGroup = cButton 

     buttonStartPosition = buttonStartPosition + newPosition 
    Next i 

但是有一个问题,当谈到去除动态创建的控件。我尝试了很多方法来删除控件。下面的代码是在点击按钮来移除控件时执行的,但它不适用于我,因此我将围绕这个圈子进行操作。如果有人能够就此问题给我一些指导,我将不胜感激。

For Each TextListBox(i).ButtonGroup In Me.Controls 
    If (TypeOf TextListBox(i).ButtonGroup Is CommandButton) Then 
     TextListBox(i).ButtonGroup.Visible = False 
    End If 
Next 

回答

1

您还没有给予了很多的信息,但你不能循环,这样 - 你需要通过数组循环:

For i = Lbound(TextListBox) to UBound(TextListBox) 
    If TypeOf TextListBox(i).ButtonGroup Is MSForms.CommandButton Then 
     TextListBox(i).ButtonGroup.Visible = False 
    End If 
Next 
+0

对不起,我只得到找回的机会给你这篇文章,但修复程序无法正常工作,因为'UBound'由于某种原因而变为-1! – user3538102 2014-09-24 12:42:19

+0

看来你的阵列已经失传了。它在哪里宣布? – Rory 2014-09-24 12:54:24