VBA对话框批量添加按钮

Visual Basic for Applications 2019-03-25

说明:这篇不是原创内容,来自ExcelHome。时间长了也忘了具体网址了,这里摘录下来方面以后查找。

1.插入一个类模块,命名为MyCla,代码如下:

Public WithEvents Butt As MSForms.CommandButton
Private Sub Butt_Click()
    Dim x, y As Integer  
    strs = Split(Butt.Tag, "|")
    x = strs(0)
    y = strs(1)
End Sub

2.插入一个用户窗体UserForm1,代码如下:

Private Sub UserForm_Initialize()
    Dim i, j As Integer
    '画按钮,默认隐藏
    For i = 0 To MAPHEIGHT - 1 '行
        For j = 0 To MAPWIDTH - 1 '列
            Set buttons(i, j).Butt = UserForm1.Controls.Add("Forms.Commandbutton.1")
            With buttons(i, j).Butt
                .Caption = ""
                .Height = 18
                .Width = 18
                .Tag = i & "|" & j
                .PicturePosition = 12
                .Visible = False
                '.Caption = i & j
                If i = 0 Then
                    .Top = 10
                Else
                    .Top = buttons(i - 1, j).Butt.Top + 18
                End If
                If j = 0 Then
                    .Left = 150
                Else
                    .Left = buttons(i, j - 1).Butt.Left + 18
                End If
            End With
        Next
    Next
End Sub

效果图:

知识共享署名声明
本文由 herokay 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论