如何在工作表上获得光标的(X,Y)坐标?

sir*_*ain 6 excel vba excel-vba

我希望能够创建一个图形,其左上角位于我的光标位置.那可能吗?可以将鼠标的(X,Y)转换为范围格式吗?

Bru*_*yne 12

嗯,它不完全是在AFAIK中构建的,但我发现这个页面给出了一个对我有用的建议:

在一个模块中,将它放在顶部:

Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Declare Function ScreenToClient Lib "user32" (ByVal hWnd As Long, _
    lpPoint As POINTAPI) As Long
    Private Type POINTAPI
    X As Long
    Y As Long
End Type
Run Code Online (Sandbox Code Playgroud)

然后,对于获取mouseX和mouseY的子例程,将其放在下面的某处:

Function MouseX(Optional ByVal hWnd As Long) As Long
' Get mouse X coordinates in pixels
'
' If a window handle is passed, the result is relative to the client area
' of that window, otherwise the result is relative to the screen
    Dim lpPoint As POINTAPI
    Application.Volatile(false)
    GetCursorPos lpPoint
    If hWnd Then ScreenToClient hWnd, lpPoint
    MouseX = lpPoint.X
End Function
Run Code Online (Sandbox Code Playgroud)

和

Function MouseY(Optional ByVal hWnd As Long) As Long
' Get mouse Y coordinates in pixels
'
' If a window handle is passed, the result is relative to the client area
' of that window, otherwise the result is relative to the screen

    Dim lpPoint As POINTAPI
    Application.Volatile(false)
    GetCursorPos lpPoint
    If hWnd Then ScreenToClient hWnd, lpPoint
    MouseY = lpPoint.Y
End Function
Run Code Online (Sandbox Code Playgroud)

然后,在Excel中,如果您只是进入一个单元格,=mouseX()它将在您点击时返回mouseX位置ENTER.与...相同=mouseY().

尝试一下,我做了:

Sub chart_Test()

    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlLine
    ActiveSheet.Shapes("Chart 1").Top = MouseY()
    ActiveSheet.Shapes("Chart 1").Left = MouseX()

End Sub
Run Code Online (Sandbox Code Playgroud)

并得到它的工作.

编辑:注意,我在图表中不如VBA中的其他东西那么好,因此当您创建图表时,您需要将部件编辑为.Shapes("Chart 1").您所在的任何图表名称/编号.或者遍历它们.