VBA - getting name of the label in mousemove event

这一生的挚爱 提交于 2019-12-02 18:02:36

问题


I have following problem. I have a lot of labels in my worksheet named in a structured way (Label1, Label2, ..., Label9) and mousemove-event macros assigned to all of them. I want to get ith value in table A1:A9, where "i" is a number of label, which is currently "touched". Is there a simple way to get label's name during mouse_move event (or some other events like Change_event). It would be look simmilar to this

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

Thanks for any help


回答1:


You can use a class module and WithEvents to do what you need. The following code should get you going in the right direction:

'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

And in your userform code module:

Dim MouseMove As New weMouseMove

Private Sub UserForm_Initialize()
    MouseMove.LabelsToTrack Array(Me.Label1, Me.Label2)
End Sub


来源:https://stackoverflow.com/questions/22484792/vba-getting-name-of-the-label-in-mousemove-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!