Programatically inserting click event code for dynamically generated label not working

前端 未结 1 999
终归单人心
终归单人心 2020-12-19 16:25

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

相关标签:
1条回答
  • 2020-12-19 16:51

    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
    
    0 讨论(0)
提交回复
热议问题