gpt4 book ai didi

vba - 形状上的双击事件

转载 作者:行者123 更新时间:2023-12-02 12:11:39 25 4
gpt4 key购买 nike

在我的研究中,我发现没有内置功能可以在 Excel 工作表上的形状上启用双击事件。我看到的许多解决方法都涉及编写类或其他类似的东西来添加此功能,所有这些似乎都超出了我的 VBA 知识库。因此,我编写了上面的代码(目前只是作为测试)来尝试编写我自己的形状双击功能。

Public Clicked As Boolean, LastClickObj As String, LastClickTime As Date


Sub GenerateShapes()
Dim sheet1 As Worksheet, shape As shape
Set sheet1 = ThisWorkbook.Worksheets("Sheet1")
Set shape = sheet1.Shapes.AddShape(msoShapeDiamond, 50, 50, 5, 5)
shape.OnAction = "ShapeDoubleClick"
Set shape = sheet1.Shapes.AddShape(msoShapeRectangle, 50, 60, 5, 5)
shape.OnAction = "ShapeDoubleClick"
LastClickTime = Now
End Sub


Sub ShapeDoubleClick()

If Second(Now) - Second(LastClickTime) > 0.5 Then
Clicked = False
LastClickObj = ""
LastClickTime = Now
Else

If Not Clicked Then
Clicked = True
LastClickObj = Application.Caller
ElseIf LastClickObj = Application.Caller Then
MsgBox ("Double Click")
Clicked = False
LastClickObj = ""
LastClickTime = Now - 1
Else
LastClickObj = Application.Caller
Clicked = True
LastClickTime = Now
End If
End If


End Sub

但是,考虑到我合并计时器的方式,如果我快速连续单击三次,代码通常只会执行“双击”。我认为这与我处理 Clicked 超时“重置”的方式有关,但逻辑上可能存在其他问题。关于如何在不添加其他大量内容(如类等)的情况下正确实现此功能的任何想法?

最佳答案

花了更多时间查看此问题,并通过一些调试意识到三次单击是由我单击的 bool 值引起的。我下面的解决方案工作得很好,包括形状区别,并且可以在代码中轻松调整点击延迟(我可以将其调整为其他地方设置的变量,但目前硬编码功能就足够了)。在这里发布我的解决方案,供 future 希望向其形状添加双击操作的用户使用

Option Explicit

Public LastClickObj As String, LastClickTime As Date

Sub ShapeDoubleClick()

If LastClickObj = "" Then
LastClickObj = Application.Caller
LastClickTime = CDbl(Timer)
Else
If CDbl(Timer) - LastClickTime > 0.25 Then
LastClickObj = Application.Caller
LastClickTime = CDbl(Timer)
Else
If LastClickObj = Application.Caller Then
MsgBox ("Double Click")
LastClickObj = ""
Else
LastClickObj = Application.Caller
LastClickTime = CDbl(Timer)
End If
End If
End If

End Sub

关于vba - 形状上的双击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38205549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com