Gruppe
VBE
Bereich
Prozedur
Thema
Neue Schaltfläche mit zugehörigem Code in Tabellenblatt
Problem
Wie kann ich auf in ein Tabellenblatt eine neue Schaltfläche mit zugehörigem Code einfügen lassen? Nach betätigung dieser Schaltfläche soll sie einschließlich Code wieder gelöscht werden.
Lösung
Geben Sie den nachfolgenden Code in ein Standardmodul ein und weisen Sie ihn einer Schaltfläche zu.
ClassModule: Tabelle1
Private Sub cmdCreateButton_Click()
Dim oBtn As Button
Dim sCode As String
sCode = "Sub cmdNew_Click" & vbLf
sCode = sCode & " Msgbox ""Hat funktioniert!""" & vbLf
sCode = sCode & _
" ActiveSheet.Buttons(Application.Caller).Delete " & vbLf
sCode = sCode & " With ThisWorkbook.VBProject.VBComponents" & _
"(""basMain"").CodeModule" & vbLf
sCode = sCode & " .DeleteLines 1, .CountOfLines" & vbLf
sCode = sCode & " End With" & vbLf
sCode = sCode & "End Sub"
Set oBtn = Buttons.Add(100, 100, 70, 20)
With oBtn
.Caption = "Meldung"
.OnAction = "cmdNew_Click"
End With
With ThisWorkbook.VBProject.VBComponents("basMain").CodeModule
.AddFromString sCode
End With
End Sub