VBA - 双击插入的图像时如何运行函数

时间:2017-11-24 07:44:01

标签: excel vba excel-vba eventtrigger

双击插入的图像时如何触发excel vba功能?现在,该功能由Private Sub Workbook_AfterSave(ByVal Success As Boolean)触发。

我只能在单击单元格或单击超链接时找到示例,但无法找到双击图像的示例。

2 个答案:

答案 0 :(得分:2)

Excel图片没有Double Click事件(如Access)。工作表有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

我不确定如何检查它是否是双击的图像 - 如果它不是一个被选中的单元格,Application.Caller会返回错误。

您可以将图像放在单元格后面,作为背景图像,然后双击其上方的单元格。

或者,我想你可以让图像的指定宏检查自上次点击以来它已经存在了多长时间。如果图像在400毫秒内被点击两次,此示例将显示MsgBox

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

答案 1 :(得分:1)

您可以将OnAction属性指定给在单击事件后激活过程的形状。

添加了矩形的代码示例

当然,您可以轻松修改现有形状。

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