Search code examples
excelvbauserform

Sidebar expanding when mouse hovers over in VBA userform


I am attempting to make a sidebar that expands/appears when the mouse hovers over it. I am using a frame for the side bar.

How sidebar should look before expanding

How sidebar should look after expanding

My sub:

Sub sidebar_showhide()
    If Me.SideBar.Width = 60 Then
        Me.SideBar.Width = 160
        Me.LLC_SideBar.Width = 160
        Me.Image3.Width = 150
        ''Me.Image3.Picture = LoadPicture("...")
        Exit Sub
    Else
        Me.SideBar.Width = 60
        Me.LLC_SideBar.Width = 60
        Me.Image3.Width = 50
        ''Me.Image3.Picture = LoadPicture("...")
        Exit Sub
    End If
End Sub

This works fine when called with the MouseUp event, but is it possible to code it with the MouseMove event without the selection statements endlessly looping because the sub gets triggered even if the user is hovering inside the form. I tried to come up with a function that detects when the mouse moves out and in the form but couldn't crack it.

Any help is appreciated.


Solution

  • Try the following - no mouse button involved. In the moment the sidebar is entered, it will enlarge, in the moment it is left, it will shrink.

    Const showWidth = 120
    Const hideWidth = 60
    
    Private Sub Sidebar_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
        showBar
    End Sub
    
    Private Sub UserForm_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
        HideBar
    End Sub
    
    Private Sub showBar()
        If Sidebar.Width < 120 Then Sidebar.Width = showWidth
    End Sub
    
    Private Sub HideBar()
        If Sidebar.Width > 60 Then Sidebar.Width = hideWidth
    End Sub
    

    However, you need to take care about the case that the enlarged sidebar is partly hiding a control of the rest of the form. When the user moves the mouse out of the sidebar and directly into that control, the UserForm_MouseMove-event will not be triggered. In that case, you will have to add MouseMove-Eventhandler for those controls (that also call HideBar)

    And it can also be that you have controls on the sidebar that are partly hidden when the sidebar is not enlarged. The use could move the mouse directly to that control and the MouseMove-event of the sidebar is not triggered: Add a MouseMove-Eventhandler for those controls (that also call ShowBar)