我有excel项目,包括图片。我有一个有ImageBox的用户表单。此窗体使用选择更改事件根据行号动态显示图片。
单元格选择更改时触发此事件。但我想通过单击shape来触发此事件。有什么解决方案吗?
请看图片。
这些是单元格选择更改事件的代码。
Private Sub App_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
Application.ScreenUpdating = False
Dim Pic As Shape
For Each Pic In ActiveSheet.Shapes
If Pic.TopLeftCell.Row = ActiveCell.Row Then
If Pic.Type = msoPicture Then
Pic.Select
Dim sheetName As String, MyPicture As String, strPicPath As String
sheetName = ActiveSheet.Name
MyPicture = Selection.Name
strPicPath = SavedPictureTo(MyPicture)' This function save image
Load ImageViever 'ImageViewer is UserForm name
With ImageViever
.Image1.Picture = LoadPicture(strPicPath)
.Show vbModeless
End With
Exit For
End If
End If
Next
Application.ScreenUpdating = True
End Sub
发布于 2021-06-09 16:01:13
正如注释中所写的,您可以将(无参数) Sub分配给单击形状时执行的形状。
在Excel中,您可以通过右键单击形状并选择“分配宏”来分配宏。
使用VBA,您可以将宏的名称写到形状的OnAction
-property中:
Dim sh As Shape
For Each sh In ActiveSheet.Shapes ' <-- Select the sheet(s) you need
sh.OnAction = "HelloWorld" ' <-- Change this to the name of your event procedure
Next
如果要知道单击的是哪个形状,可以使用Application.Caller
属性。当通过单击形状调用宏时,它包含该形状的名称。
Sub helloWorld()
Dim sh As Shape
On Error Resume Next
Set sh = ActiveSheet.Shapes(Application.Caller)
On Error GoTo 0
If sh Is Nothing Then
MsgBox "I was not called by clicking on a shape"
Else
MsgBox "Someone clicked on " & sh.Name
End If
End Sub
https://stackoverflow.com/questions/67899449
复制相似问题