1

我尝试做的是:

1. goto `worksheet 4`
2. right mouse click on cell `D32`
3. if (first time): 
      a. choose import text file.
   else:
      b. choose the Refresh 
  • 除了使用mouse_events之外,还有什么更优雅的方法 吗?
  • 如果我使用mouse_events我必须模拟一个左键和一个右键单击。如何确保右键单击菜单上的确切位置?我想使用spy++,但这似乎是做简单事情的错误和肮脏的方式。

====链接中的源代码来模拟鼠标事件: ====

Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
Public Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
Public Const MOUSEEVENTF_LEFTDOWN = &H2
Public Const MOUSEEVENTF_LEFTUP = &H4
Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
Public Const MOUSEEVENTF_RIGHTUP As Long = &H10

Private Sub SingleClick()
  SetCursorPos 100, 100 'x and y position
  mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
  mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
End Sub

Private Sub DoubleClick()
  'Simulate a double click as a quick series of two clicks
  SetCursorPos 100, 100 'x and y position
  mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
  mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
  mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
  mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
End Sub

Private Sub RightClick()
  'Simulate a right click
  SetCursorPos 200, 200 'x and y position
  mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
  mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
  mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
  mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
End Sub
4

1 回答 1

1

除了使用 mouse_events 之外,还有什么更优雅的方法吗?

就在这里。使用Worksheet_BeforeRightClick事件

同样在下面的示例中,我正在检查 Cell D32 中是否有任何内容来决定是导入还是刷新。如果您愿意,可以使用布尔变量。

代码进入相关工作表的工作表代码区域。见截图。

截屏

在此处输入图像描述

代码

Option Explicit

Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
    On Error GoTo Whoa

    Application.EnableEvents = False

    '~~> Check if the right click happened on D32
    If Not Intersect(Target, Range("D32")) Is Nothing Then
        '~~> Check if cell is empty
        If Len(Trim(Target.Value)) = 0 Then
            '~~> If empty, import file
        Else
            '~~> if not empty, refresh data
        End If
        Cancel = True
    End If

LetsContinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

高温高压

于 2012-11-23T09:53:43.727 回答