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

最佳答案

嗯,它不是完全基于AFAIK构建的,但是我发现this page给出了对我有用的建议:

在模块中,将其放在顶部:

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

然后,为了使子例程获取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


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

然后,在Excel中,如果您仅输入一个单元格=mouseX(),则在您单击ENTER时将返回mouseX位置。与=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

并使其起作用。

编辑:注意,我对图表的使用不如VBA中的其他功能好,因此在创建图表时,您需要将.Shapes("Chart 1").部分编辑为所使用的图表名称/编号。或遍历它们。

关于vba - 如何获得工作表上光标的(X,Y)坐标?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31794399/

10-10 02:01