Try this code:
Code:
Option Explicit
Dim WithEvents DynamicCommandButton As CommandButton
Private Sub DynamicCommandButton_Click()
MsgBox "My Name is: " & DynamicCommandButton.Name
End Sub
Private Sub Form_Load()
Set DynamicCommandButton = Me.Controls.Add("VB.CommandButton", "cmd")
With DynamicCommandButton
.Caption = "Dynamic Control"
.Visible = True
End With
End Sub
Also to do the same with API:
Code:
Private Declare Function CreateWindowEx Lib "user32" Alias "CreateWindowExA" (ByVal dwExStyle As Long, ByVal lpClassName As String, ByVal lpWindowName As String, ByVal dwStyle As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hWndParent As Long, ByVal hMenu As Long, ByVal hInstance As Long, lpParam As Any) As Long
Private Const WS_CHILD = &H40000000
Private Const WS_VISIBLE = &H10000000
Private Sub Form_Load()
Dim hWnd_Btn As Long
hWnd_Btn = CreateWindowEx(0, "Button", "Button1", WS_CHILD Or WS_VISIBLE, 32, 32, 64, 64, hWnd, 0, App.hInstance, 0)
End Sub