我希望能够创建一个图形,其左上角位于我的光标位置。那可能吗?可以将鼠标的(X,Y)转换为范围格式吗?
答案 0 :(得分:12)
嗯,它不完全是在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").
部分编辑为任何图表名称/编号你继续。或者遍历它们。
答案 1 :(得分:4)
不确定鼠标x y但是您可以获得工作表选择更改的范围。将图表放在该位置。
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Chart.Left = Target.column
Chant.Top = Target.row
End Sub