【Excel/VBA】フォームコントロールを動的に生成してボタンイベントを発生させ方法
Excelマクロのフォームコントロールであらかじめ描かずVBA上で描くことができます。今回の例では実行時にLabel, TextBox, CommandButtonを生成し且つボタン押下時にイベントを発生させています。
動きについてはこちらの動画をご覧ください。
下図のように実行時にコントロールが現れます。ボタンを押すとテキストボックスに「OK」という文字が現れるようになっています。
ソースコードはこちら。
Dim myLabel As MSForms.Label Dim myTextBox As MSForms.TextBox Dim WithEvents myButton As MSForms.CommandButton Private Sub UserForm_Initialize() Set myLabel = Controls.Add("Forms.Label.1", "Label1") Set myTextBox = Controls.Add("Forms.TextBox.1", "TextBox1") Set myButton = Controls.Add("Forms.CommandButton.1", "CommandButton1") Call setStyle(myLabel, "ITEM", 10, 10, 80, 30) Call setStyle(myTextBox, "", 10, 100, 100, 30) Call setStyle(myButton, "OK", 50, 50, 100, 30) End Sub Private Sub myButton_Click() myTextBox.Text = "OK" End Sub Private Sub setStyle(ctl, caption_, top_, left_, width_, height_) If TypeName(ctl) = "Label" Or TypeName(ctl) = "CommandButton" Then ctl.Caption = caption_ End If ctl.Top = top_ ctl.Left = left_ ctl.Width = width_ ctl.Height = height_ End Sub
スポンサーリンク