Search code examples
vbaexceleventtrigger

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


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.


Solution

  • 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