Excel & VBA---Brain Training


  • 01

UserForm을 Run Time에 만들기

아래 구문을 실행하면 UserForm 자체가
자동으로 생성된다..

Sub createUserFormRunTime()
Dim oForm As Object
Dim oFrame As MSForms.Frame
Dim oButton As MSForms.CommandButton
Dim oListBox As MSForms.ListBox
Dim iX As Integer

Application.VBE.MainWindow.Visible = False
Set oForm = ThisWorkbook.VBProject.VBComponents.Add(3)

With oForm
    .Properties("Caption") = "UNO_CODE_LIBRARY"
    .Properties("Width") = 300
    .Properties("Height") = 270
End With

Set oListBox = oForm.designer.Controls.Add("Forms.listbox.1")
With oListBox
    .Name = "lstTest"
    .Width = 150
    .Height = 230
    .Top = 10
    .Left = 10
    .Font.size = 8
    .Font.Name = "Tahoma"
    .BorderStyle = MSForms.fmBorderStyle.fmBorderStyleSingle
    .SpecialEffect = MSForms.fmSpecialEffectSunken
End With
Set oButton = oForm.designer.Controls.Add("Forms.commandbutton.1")
With oButton
    .Name = "cmdTest"
    .Caption = "목록선택후 크릭!!"
    .Top = 10
    .Left = oListBox.Left + oListBox.Width + 10
    .Width = 120
    .Height = 20
    .Font.size = 8
    .Font.Name = "Tahoma"
    .BackStyle = fmBackStyleOpaque
End With

oForm.codemodule.insertlines 2, "Private Sub UserForm_Initialize()"
For iX = 3 To 100
    oForm.codemodule.insertlines iX, "   me.lstTest.addItem """ & "SampleData_" & Format(iX, "000") & """ "
Next
oForm.codemodule.insertlines iX + 3, "End Sub"

With oForm.codemodule
    .insertlines iX + 4, "Private Sub cmdTest_Click()"
    .insertlines iX + 5, "   If me.lstTest.text <>"""" Then"
    .insertlines iX + 6, "      msgbox (""You selected item: "" & me.lstTest.text )"
    .insertlines iX + 7, "   End If"
    .insertlines iX + 8, "End Sub"
End With
VBA.UserForms.Add(oForm.Name).sHow

End Sub

아래와 같은 UserForm이 만들어지고 로딩된다



만약 에러가 난다면 아래의 그림과 같이 보안(개발자매크로설정)의
체크를 해제 하시면된다



문제는 이것을 사용하고 닫고 다시 열고 하면
UserForm이 계속 만들어질 것이다
이것은 RunTime으로 만들기 위한 목적에 맞지 않는다
사용후 UserForm자체가 사라지게 해보는 문제..
위의 구문을 조금 이해하면 된다

***[LOG-IN]***

  • 01