我想知道是否有人知道excel使用VBA或excel中的任何其他方式:
以交互方式单击以excel绘制的图形的x轴,并将x轴值输出到单元格。
有人有什么想法吗?我很难过。
答案 0 :(得分:1)
不是一项特别容易的任务......
如果您为截取图表/图表轴创建事件处理程序,那么您就可以开始了。把它放在Workbook代码模块中。打开文件后,将根据Cht
事件设置Workbook_Open
。然后Private Sub Cht_Select...
将在用户选择图表时运行。如果所选部件是轴,则会显示一个消息框。您需要想出一种方法来确定相对于轴的光标位置,并尝试计算轴值。
Option Explicit
Public WithEvents Cht As Chart
Private Sub Cht_Select(ByVal ElementID As Long, _
ByVal Arg1 As Long, ByVal Arg2 As Long)
If ElementID = xlAxis Then
MsgBox "Call your macro here to identify cursor position in chart..."
End If
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Set Cht = Nothing
End Sub
Private Sub Workbook_Open()
Set Cht = Sheet1.ChartObjects(1).Chart
End Sub
有一些关于获取鼠标光标位置的信息,在这里:
http://support.microsoft.com/kb/152969
然后你需要获得轴位置和长度并做一些简单的数学运算来计算光标所在的轴值。
这是一个稍微修改过的版本,您可以将其放入标准模块中,以返回数组中的XY坐标。由你决定如何使用图表轴对象,min / max,length,left&顶部值,以便在选择轴时计算(或近似)光标的轴值。
' Access the GetCursorPos function in user32.dll
Declare Function GetCursorPos Lib "user32" _
(lpPoint As POINTAPI) As Long
' Access the GetCursorPos function in user32.dll
Declare Function SetCursorPos Lib "user32" _
(ByVal x As Long, ByVal y As Long) As Long
' GetCursorPos requires a variable declared as a custom data type
' that will hold two integers, one for x value and one for y value
Type POINTAPI
X_Pos As Long
Y_Pos As Long
End Type
' This function retrieve cursor position:
Function Get_Cursor_Pos() As Variant
' Dimension the variable that will hold the x and y cursor positions
Dim Hold As POINTAPI
Dim xyArray(1) As Variant
' Place the cursor positions in variable Hold
GetCursorPos Hold
' Display the cursor position coordinates
xyArray(0) = Hold.X_Pos
xyArray(1) = Hold.Y_Pos
Get_Cursor_Pos = xyArray
End Function
Sub GetCoordinates()
Dim xyPosition As Variant
xyPosition = Get_Cursor_Pos
Debug.Print xyPosition(0)
Debug.Print xyPosition(1)
'### Now that you have the x and y position, you will need to perform some
' additional computations with the Axis' .top, .left, and its min/max values
' in order to get the approximate axis location where you mouse-clicked it.
End Sub