VBA – 在mousemove事件中获取标签的名称

我有以下问题。 我的工作表中有很多以结构化方式命名的标签(Label1,Label2,…,Label9)和分配给它们的mousemove事件macros。 我想在表格A1:A9中获得第i个值,其中“i”是当前“触摸”的标签的数量。 是否有一个简单的方法来获取标签的名称在mouse_move事件(或一些其他事件,如Change_event)。 这看起来是相似的

Private Sub Label47_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) Dim label_name as String Dim which_one as Integer Dim val as Integer label_name = "something like ActiveLabel.Name" which_one = CInt(right(label_name,1)) val = Cells(which_one,1).Value rest code.... End Sub 

谢谢你的帮助

你可以使用一个类模块和WithEvents做你所需要的。 下面的代码应该让你朝着正确的方向前进:

 'weMouseMove class module: Private WithEvents mLbl As MSForms.Label Private mLabelColl As Collection Sub LabelsToTrack(Labels As Variant) Set mLabelColl = New Collection Dim i As Integer For i = LBound(Labels) To UBound(Labels) Dim LblToTrack As weMouseMove Set LblToTrack = New weMouseMove Dim Lbl As MSForms.Label Set Lbl = Labels(i) LblToTrack.TrackLabel Lbl mLabelColl.Add LblToTrack Next i End Sub Sub TrackLabel(Lbl As MSForms.Label) Set mLbl = Lbl End Sub Private Sub mLbl_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, _ ByVal X As Single, ByVal Y As Single) MsgBox mLbl.Name & ": " & mLbl.Caption End Sub 

在您的用户表单代码模块中:

 Dim MouseMove As New weMouseMove Private Sub UserForm_Initialize() MouseMove.LabelsToTrack Array(Me.Label1, Me.Label2) End Sub