I am inserting a ActiveX control Label in excel sheet using VBA code. Now after inserting the button, I am trying to insert the click event code but its not working. Below i
I believe this is in continuation to your last question.
Is this what you are trying?
Option Explicit
Sub Sample()
Dim i As Long
For i = 1 To 5
AddButton "Sheet1", i
Next i
End Sub
Public Sub AddButton(strSheetName As String, counter As Long)
Dim btn As OLEObject
Dim cLeft, cTop, cWidth, cHeight
With Worksheets(strSheetName).Range("J" & (6 + counter))
cLeft = .Left
cTop = .Top
cWidth = .Width
cHeight = .Height
End With
With Worksheets(strSheetName)
Set btn = .OLEObjects.Add(ClassType:="Forms.Label.1", Link:=True, _
DisplayAsIcon:=False, Left:=cLeft, Top:=cTop, Width:=cWidth, _
Height:=cHeight)
End With
btn.Object.Caption = "Add New"
btn.Name = Left(strSheetName, 3) & counter
With ActiveWorkbook.VBProject.VBComponents( _
ActiveWorkbook.Worksheets(strSheetName).CodeName).CodeModule
.InsertLines Line:=.CreateEventProc("Click", btn.Name) + 1, _
String:=vbCrLf & _
"MsgBox ""Hello world"""
End With
End Sub
FOLLOWUP
yes, Clean the code from a particular sheet of entire Excel project. That's what is the requirement – user1269291 54 secs ago
Option Explicit
Sub Sample()
Dim strSheetName As String
strSheetName = "Sheet1"
With ActiveWorkbook.VBProject.VBComponents( _
ActiveWorkbook.Worksheets(strSheetName).CodeName).CodeModule
.DeleteLines 1, .CountOfLines
End With
End Sub