VBA Excel用户窗体。如何确定单击了哪个图像

时间:2016-10-03 14:46:24

标签: excel vba userform

我在10个ImageBox中有10个图像的用户表单。我知道我可以确定点击的图像是这样的:

Private Sub Image1_Click()
    MsgBox "Image 1 clicked!"
End Sub

但由于有10张图片,我是否需要重复上述代码的10倍?

Private Sub Image1_Click()
    MsgBox "Image 1 clicked!"
End Sub

Private Sub Image2_Click()
    MsgBox "Image 2 clicked!"
End Sub

Private Sub Image3_Click()
    MsgBox "Image 3 clicked!"
End Sub

Private Sub Image4_Click()
    MsgBox "Image 4 clicked!"
End Sub

etc

还是有一种更优雅,更简洁的方法?

1 个答案:

答案 0 :(得分:2)

您需要使用事件下沉,因此在类模块中,名为cls_CustomImage的内容具有以下内容

Private WithEvents customImage As Image

Public Sub InitialiseCustomImage(imgToCusomise As Image)
    Set customImage = imgToCusomise
End Sub
Private Sub customImage_Click()
    MsgBox customImage.Name
End Sub

然后在您的用户表单中打开以下内容

Public colCustomImages As Collection

Private Sub UserForm_Initialize()
Dim ctl As Control
Dim clsCustomImage As cls_CustomImage

Set colCustomImages = New Collection

For Each ctl In Me.Controls

    If TypeName(ctl) = "Image" Then
        Set clsCustomImage = New cls_CustomImage
        clsCustomImage.InitialiseCustomImage ctl
        colCustomImages.Add clsCustomImage
    End If

Next ctl
End Sub