2017-09-08 173 views
1

簡單地說,我嘗試過下面的示例:How to add events to Controls created at runtime in Excel with VBA但是當我點擊我的按鈕時什麼也沒有發生。無法將事件添加到VBA中的動態創建按鈕userform

問題是我不會一次創建大量按鈕,每次用戶單擊某個預先添加的按鈕時都會添加一個新按鈕。

代碼創建按鈕:

'Finally the delete button 
Dim newb As MSForms.CommandButton 
'thisQuant is a var keeping track of how many buttons there are 
Set newb = FProducts.Controls.Add("Forms.CommandButton.1", "del" & thisQuant, False) 
Dim Button As New Class1 
Set Button.delButton = newb 

而且作爲例子說明新類:

Public WithEvents delButton As MSForms.CommandButton 

Private Sub delButton_Click() 
    MsgBox "test" 
    'quantProd = CInt(NewNota.ProductQuant.Caption) 
End Sub 

我來自Python和VBA極爲混亂。

+1

可能你應該在[mcve]中顯示更多的代碼。其他解決方案應該可以工作,所以你的第一種方法應該是複製/實現*原樣*,看看是否有效。如果需要,請在新工作簿中執行此操作。我注意到在另一個解決方案中,它在窗體的構造函數中創建一個按鈕* array *:Dim ButArray()As New Class2'(其中'Class2'是您的按鈕事件類的類模塊,我似乎記得您需要將這些按鈕全部保存在內存中,儘管如此,還沒有經過長時間的測試。 –

+3

這樣做最常見的問題是忘記將Class1實例聲明爲Global(即在模塊的頂部,而不是在Sub或功能),所以它超出了範圍,並在創建按鈕的代碼退出時立即被銷燬 –

+0

@TimWilliams Yup,就是這樣,謝謝你,我剛纔意識到你可以在模塊中做出聲明,如果你想要發表一個完整的答案我會代表你 – Mojimi

回答

4

執行此類事情時最常犯的錯誤是忘記將Class1實例(或您的數組/實例集合)聲明爲Global(即在模塊的頂部,而不在Sub或Function中) 。

如果您不這樣做,那麼您的自定義類實例將超出範圍,並在創建該按鈕的代碼退出後立即銷燬。

Dim Button As Class1 

Sub CreateButton() 
    Dim newb As MSForms.CommandButton 

    '... 

    'thisQuant is a var keeping track of how many buttons there are 
    Set newb = FProducts.Controls.Add("Forms.CommandButton.1", "del" & thisQuant, False) 

    Set Button = New Class1 
    Set Button.delButton = newb 

    '... 

End Sub 
相關問題