VBA - How to run function when double click an inserted image

Viewed 4990

How to trigger excel vba function when I double-click an inserted image? Right now the function is triggered by Private Sub Workbook_AfterSave(ByVal Success As Boolean).

I could only find examples when cell is clicked or hyperlink is clicked, but couldn't find one for double-clicking on an image.

2 Answers

Excel images don't have a Double Click event (like Access). The worksheet has Worksheet_BeforeDoubleClick:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    MsgBox ("Application.Caller: " & IIf(IsError(Application.Caller), Err.Description, _
        Application.Caller) & vbLf & "Target.Address: " &  _
        IIf(IsError(Target.Address), Err.Description, Target.Address))
End Sub

I'm not sure how to check if it was an image that was double-clicked -- Application.Caller returns an error if it's not a cell that's selected.

You could put the image behind the cells, as a background image, and act on double click of the cells above it.

.

Or, I suppose you could make the image's assigned macro check how long it's been since the last time it was clicked. This example will show a MsgBox if the image is clicked twice within 400ms:

Public clickedPic As String
Public lastTimer As Single

Sub Picture2_Click()
    clickedPic = Application.Caller
    If (Timer - lastTimer) < 0.5 Then
        MsgBox "doubleclick"
        er
    End If
    lastTimer = Timer
Debug.Print clickedPic, Now()
End Sub

You can assign the OnAction property to the shape activating a procedure after a click event.

Code Example with added Rectangle

Of course you can modify this easily for an existing shape.

Sub AddRectangle()
Dim oSht As Worksheet
Dim oShape As Shape
Set oSht = ThisWorkbook.Worksheets("MySheet")
' only if you want to add a new shape, otherwise refer to Name or item no
  Set oShape = oSht.Shapes.AddShape(msoShapeRectangle, 100, 100, 50, 50)
  oShape.Name = "MyRectangle"
' OnAction property assignes the specified procedure (e.g. "MyProcedure") to the shape object.
  oSht.Shapes("MyRectangle").OnAction = "MyProcedure"
End Sub

Sub MyProcedure()
MsgBox "Shape MyRectangle has been clicked."
End Sub
Related