简体   繁体   English

VBA Excel 用户窗体。 如何判断哪张图片被点击

[英]VBA Excel UserForm. How to determine which image has been clicked

I have a userform with 10 images inside 10 ImageBoxes.我有一个包含 10 个图像框内的 10 个图像的用户表单。 I know that I can determine what image has been clicked like this:我知道我可以像这样确定点击了什么图像:

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

But as there are 10 images, do I have to repeat 10 times the above code?但是因为有 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

Or there's a more elegant and concise method?或者有更优雅简洁的方法吗?

You need to use event sinking, so in a class module, called cls_CustomImage have the following您需要使用事件接收器,因此在名为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

Then in your user form opening have the following然后在您的用户表单中打开以下内容

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM