我有一个用户表单,10 个图像框中有 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
或者有更优雅简洁的方法吗?
最佳答案
您需要使用事件接收,因此在名为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
关于excel - VBA Excel 用户窗体。如何判断哪个图片被点击了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39834367/