I’ve been experimenting with adding buttons to a worksheet. I have a macro that works fine:
Option Explicit Sub SimpleAdd() Dim s As String Dim btn As OLEObject ' Add the button With ActiveCell s = .Address(False, False) Set btn = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _ Link:=False, DisplayAsIcon:=False, _ Left:=.Left, Top:=.Top, Width:=.Width, Height:=.Height) End With btn.Name = "btn" & s btn.Object.Caption = s ' Add the code With ThisWorkbook.VBProject.VBComponents(ActiveSheet.CodeName).CodeModule Dim n As Long n = .CountOfLines .InsertLines n + 1, "Private Sub " & btn.Name & "_Click()" .InsertLines n + 2, "MsgBox ""Click on " & s & """" .InsertLines n + 3, "End Sub" End With End Sub
However,I do not want to add the button click code to the worksheet’s code module. So, I am using a class instead. The class code is in a Class called cPopBtn:
Option Explicit Private mBtn As OLEObject Private WithEvents btnControl As MSForms.CommandButton Private mAdr As String Public Sub Init(cell As Range) Dim ws As Worksheet Set ws = cell.Parent mAdr = cell.Address(False, False) With cell Set mBtn = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _ Link:=False, DisplayAsIcon:=False, _ Left:=.Left, Top:=.Top, Width:=.Width, Height:=.Height) Set btnControl = mBtn.Object btnControl.Caption = mAdr End With End Sub Private Sub btnControl_Click() MsgBox "Class from " & mAdr End Sub
And the macro to create the cPopBtn objects is:
Option Explicit Private mPopBtns() As cPopBtn Private mCount As Integer Sub ClassyAdd() ReDim Preserve mPopBtns(mCount) Set mPopBtns(mCount) = New cPopBtn mPopBtns(mCount).Init ActiveCell mCount = mCount + 1 End Sub Sub Dump() MsgBox "Count is " & mCount End Sub
The “ClassyAdd” creates buttons on the worksheet, but the object disappears. If you run ClassyAdd and then Dump, mCount is still zero and the mPopBtns array is empty just as if a VBA Reset has occured. Any clues as to why the class does not work? I have attached the worksheet. TIA –Sam