Demo dynam. erzeugter CmdBtn mit Makro
19.02.2017 00:31:46
littletramp
Hallo Sascha
Ich habe dir eine Demo erstellt, die zeigt wie es geht https://www.herber.de/bbs/user/111569.xlsm
Die Demo besteht aus einem Klassenmodul, einer (leeren) UserForm und einem Standardmodul.
Hier der Code in den einzelnen Modulen:
Klassenmodul: clsCmdButton
Option Explicit
Public WithEvents CmdButton As MSForms.CommandButton
Private Sub CmdButton_Click()
Dim i As Integer
Dim proc As String, arg As String
i = InStr(CmdButton.Tag, ",")
If i = 0 Then ' ohne Argument
proc = CmdButton.Tag
Application.Run proc
Else ' mit Argument
proc = Left(CmdButton.Tag, i - 1)
arg = Right(CmdButton.Tag, Len(CmdButton.Tag) - i)
Application.Run proc, arg
End If
End Sub
UserForm: frmDynCmdButton
Option Explicit
Private ctlCmdButtons() As New clsCmdButton
Private Sub UserForm_Initialize()
Dim i As Integer
' Anzahl Buttons abfragen
Do
i = Application.InputBox(Prompt:="Anzahl Buttons [3..10]", Default:=5, Type:=1)
Loop While i 10
CreateDynamicButtons i
End Sub
Private Sub CreateDynamicButtons(intCount As Integer)
Dim i As Integer
Dim intTop As Integer
Dim ctlItem As Control
Const cintSpace = 5
Const cintWidth = 100
Const cintHeight = 20
Me.Caption = Me.Name
' Grösse der UserForm berechnen
intTop = cintSpace
Me.Height = 20 + intCount * cintHeight + (intCount + 1) * cintSpace
Me.Width = 5 + cintWidth + 2 * cintSpace
' CommandButtons erzeugen
For i = 1 To intCount
intTop = cintSpace + (i - 1) * (cintHeight + cintSpace)
' CommandButton erzeugen
Set ctlItem = Me.Controls.Add("Forms.CommandButton.1")
' CommandButton erzeugen
With ctlItem
.Top = intTop
.Left = cintSpace
.Width = cintWidth
.Height = cintHeight
' Beschriftung und ControlTipTexte festlegen
Select Case i
Case intCount
.Caption = "UserForm schliessen"
Case Else
.Caption = "Button " & i
End Select
' Aufzurufender Makro und Argumente festlegen -> Syntax: Makroname, Arg1, Arg2, ...
Select Case i
Case intCount ' Schliessen-Button
.Tag = "UserFormClose" ' Sub UserFormClose ohne Argument
Case Else
.Tag = "CmdButton, " & i ' Sub CmdButton mit Argument, WICHTIG: mit Komma
End Select
End With
ReDim Preserve ctlCmdButtons(i - 1)
Set ctlCmdButtons(i - 1).CmdButton = ctlItem
Next
End Sub
Standardmodul: modHandleCmdBtn
Option Explicit
Public Sub ShowUserForm()
frmDynCmdButton.Show
End Sub
' Prozeduren, die von den dynamischen
' Schaltflächen aufgerufen werden
Public Sub CmdButton(Nummer As Integer)
MsgBox "Argument: " & Nummer
End Sub
Public Sub UserFormClose()
Unload frmDynCmdButton
End Sub
Gruss Markus