Hm, it is not exactly built in AFAIK, but I found this page which contains a sentence that worked for me:
In the module, put this at the top:
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
Then for the routines, to get mouseX and mouseY, put this below:
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
and
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
Then, in Excel, if you just go into cell =mouseX() , it will return the mouseX position when you press ENTER . Same thing with =mouseY() .
Trying this, I did:
Sub chart_Test() ActiveSheet.Shapes.AddChart.Select ActiveChart.ChartType = xlLine ActiveSheet.Shapes("Chart 1").Top = MouseY() ActiveSheet.Shapes("Chart 1").Left = MouseX() End Sub
and make it work.
edit: Notice I'm not as good at charts as other things in VBA, since you are creating charts, you need to edit the .Shapes("Chart 1"). part .Shapes("Chart 1"). for any name / number of the chart you are on. Or iterate through them.