user2280549
user2280549

Reputation: 1234

VBA - getting name of the label in mousemove event

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

Upvotes: 0

Views: 5920

Answers (1)

mwolfe02
mwolfe02

Reputation: 24207

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

Upvotes: 1

Related Questions