在VB中动态添加控件

代码如下:

主要功能是在FORM上动态添加一个或多个控件。

 1 Option Explicit

 2 Dim oCtrl As Object

 3 '使得控件可以响应事件

 4 Dim WithEvents MyBtn As CommandButton

 5 Private Sub Form_Load()

 6 Dim i As Integer

 7     '先在窗体上加载个Label1(0)的标签控件

 8     For i = 1 To 3

 9         Load Me.Label1(i)

10         Label1(i).Top = Label1(i - 1).Top + 2 * Label1(0).Height

11         Label1(i).Caption = "Label1(" & i & ")"

12         Label1(i).Visible = True

13     Next

14     'Debug.Print Me.Label1.Count

15     LoadControl

16     LoadControlWithEvents

17 End Sub

18 Private Sub LoadControl()

19     Set oCtrl = Controls.Add("VB.CommandButton", "Button1")

20     With oCtrl

21         .Caption = "不会响应事件的按钮"

22         .Width = 2000

23         .Left = 100

24         .Top = 200

25         .Visible = True '控件加载后默认为不可见,故此步骤至关重要!

26     End With

27 End Sub

28 Private Sub LoadControlWithEvents()

29     Set MyBtn = Controls.Add("VB.CommandButton", "Button2")

30     With MyBtn

31         .Caption = "我可以响应事件!"

32         .Width = 1800

33         .Left = 100

34         .Top = 700

35         .Visible = True

36     End With

37 End Sub

38 Private Sub MyBtn_Click()

39     MsgBox "我要移除动态加载的控件了!"

40     Me.Controls.Remove "Button1"

41     Me.Controls.Remove "Button2"

42 End Sub

引自:百度知道-http://zhidao.baidu.com/question/5248806.html&__bd_tkn__=6fbc413b2a218731570caa66aeac19fe880c91fa8078338d51fed8133ea5c69d362ad36bb4bcda3b39bb3949f6bbe47087ac3af56e60b1f4e7eb60157d5ef93a9567afe6065506c64a7e3108d146ba0f3a70ee030f59c3fed43d40740029445fca170e4649c7d8d9e919fdb9cfde800ec9342bf0

你可能感兴趣的:(vb)