我想知道是否有人知道在 excel 中使用 VBA 的方法或在 excel 中的任何其他方法:
以交互方式单击 Excel 中绘制的图形的 x 轴,该 x 轴值将输出到单元格。
有人有想法么?我很难过。
不是一个特别容易的任务...
如果您在查看图表/图表轴时创建一个事件处理程序,那将帮助您入门。把它放在工作簿代码模块中。当文件打开时,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 坐标。由您决定如何将这些与图表轴对象、最小/最大值、长度、左侧和顶部值一起使用,以便在选择轴时计算(或近似)光标的轴值。
' 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