Wednesday, November 2, 2016

Excel VBA drag control by mouse

In some cases you may need to drag a frame or any ActiveX control by mouse within the user form. This can be easily done by implementing the following code.



' Declare shared variables that will be used in different subs
Dim XOld, YOld As Single
Dim DragStart As Boolean

Private Sub UserForm_Initialize()
DragStart = False
End Sub

Private Sub Frame1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
If Button = 1 Then     'If the left mouse key button is pressed on the frame, then start the drag behaviour
DragStart = True
XOld = X
YOld = Y
End If
End Sub

Private Sub Frame1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
If DragStart = True Then
Frame1.Left = Frame1.Left + (X - XOld)     'Move in X direction with the corresponding displacement in X
Frame1.Top = Frame1.Top + (Y - YOld)     'Move in Y direction with the corresponding displacement in Y
End If
End Sub

Private Sub Frame1_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
If Button = 1 Then
DragStart = False     'If mouse key released then stop drag behaviour
End If
End Sub



Tags:

Excel VBA drag control by mouse

Excel VBA drag frame by mouse left click

Excel VBA drag ActiveX control using mouse

Excel VBA drag and drop