2014-09-24 88 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