I have an existing CommandButton in a Form called cmd0001 and it has its event handler hardcoded in the module of the form.
Private Sub cmd0001_Click()
'code
End Sub
I need to "disable" that button by changing its behavior programmatically (in runtime). One possibility is to change the code of the procedure in the module using InsertLines:
Set vbComp = ThisWorkbook.VBProject.VBComponents("formName")
Set vbModule = vbComp.CodeModule
linenr = vbModule.ProcStartLine("cmd0001_Click", vbext_pk_Proc)
vbModule.InsertLines linenr + 2, "msgbox ""no"": exit sub"
Sadly this is a protected VBAProject and I get the error: "Run-time Error 50289 Can't perform operation since the project is protected".
It is possible to change the click event handler of the button? Actually I will work with many buttons and ideally I would like to have 1 global event handler for the "disabled" buttons.
All examples I found by now works with dynamically created buttons like this example but I can't find an example on how to do it with a button that already exists.
Edit 1:
Ok, I have found that is possible to create a class module and create a click handler using the following code:
'in form
Dim btnH As cCtrlHandler
Set btnH = New cButtonHandler
Set btnH.ctrl = btnTest
'class module cButtonHandler
Public WithEvents ctrl As MSForms.CommandButton
Private Sub ctrl_Click()
MsgBox "Not authorized!"
End Sub
But the main problem is that the click handler is not overwritten! The new code, in this example the 'MsgBox "Not authorized!"' is appended to the existing code. It is possible to overwrite the event handler completely?