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

我希望能够创build一个graphics,其左上angular位于我的光标位置。 那可能吗? 我的鼠标的(X,Y)可以转换成范围格式吗?

不知道关于鼠标xy,但你可以得到工作表select变化的范围。 把图表放在那个位置。

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

嗯,这不是完全build立在AFAIK,但我发现这个页面 ,给出了一个build议,为我工作:

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

 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 

然后,让子程序得到鼠标X和鼠标Y,把它放在下面的地方:

 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中,如果您只需input一个单元格=mouseX()则它将在您按下ENTER时返回鼠标的X位置。 同=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中的其他东西那么好,所以当你创build图表时,你需要编辑.Shapes("Chart 1"). 部分无论您的图表名称/号码。 或者遍历它们。