Search code examples
excelvbauserform

Moving a shape when running a userform


I'm trying to "unlock" a fixed image on an already running userform so that I can move it around freely and after clicking it again, cause it to be in a fixed position again.


Solution

  • Think that this does what you are looking for.

    Dim imgOriginX As Double
    Dim imgOriginY As Double
    Dim clicked As Boolean
    
    Private Sub UserForm_Activate()
        clicked = False
    End Sub
    
    Private Sub Image1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
         If clicked = True Then
            imgOriginX = X
            imgOriginY = Y
        End If
    End Sub
    
    Private Sub Image1_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
        If clicked = True Then
            clicked = False
        Else
            clicked = True
        End If
    End Sub
    
    Private Sub Image1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
         If clicked = True Then
            If Button And 1 Then
                Image1.Left = Image1.Left + (X - imgOriginX)
                Image1.Top = Image1.Top + (Y - imgOriginX)
            End If
        End If
    End Sub