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

ef1yzkbh  于 2023-06-25  发布在  其他
关注(0)|答案(2)|浏览(207)

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

pxy2qtax

pxy2qtax1#

嗯,它并不是完全内置在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").部分编辑为你所使用的任何图表名称/编号。或者通过迭代。

z0qdvdin

z0qdvdin2#

不确定鼠标x y,但你可以得到工作表选择范围的变化。将图表放在该位置。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Chart.Left = Target.column
    Chant.Top  = Target.row
End Sub

相关问题