Search code examples
excelvba

excel open UserForm1 without excelfile opens


I asked the same question for a Word document and got an answer. Now it's my turn in Excel and unfortunately the same structure of the code does not work here. There are similar questions in the forum but without an answer unfortunately.

I only want to open my UserForm1 in Excel with VBA without the excel opens.

My code for "ThisWorkbook" looks like this: But I have the problem that in the background file is grayed see picture.

Private Sub Workbook_Open()

    ThisWorkbook.Windows(1).Visible = False
    UserForm1.Show vbModeless
End Sub

In the forum the answer is Application.quit and similar which do not work, because then another open document closes, but I don't want that, I just want this document to be affected.

UserForm1 with gray background excel


Solution

  • The following logic hides the workbook but continues to show other open Excel files. If no other Excel file is open, it uses Application.Visible = False to hide the Excel Application Window.

    Put the following Sub and Function into a regular Module. In theory, you could put everything into the workbook.open-Trigger, but that makes it hard to test. I think it's good programming practice to keep trigger code as short as possible.

    Sub showLoginForm()
        If isSheetVisible Then
            ' Only Hide this workbook and keep the other workbooks visible
            ThisWorkbook.Windows(1).Visible = False
        Else
            ' There is no other workbook visible, hide Excel
            Application.Visible = False
        End If
        UserForm1.Show
    End Sub
    
    Function isSheetVisible() As Boolean
        ' Checks if any workbook except the current one is visible
        Dim wb As Workbook
        
        For Each wb In Application.Workbooks
            If Not wb Is ThisWorkbook Then
                Dim win As Window
                For Each win In wb.Windows
                    If win.Visible Then isSheetVisible = True
                Next
            End If
        Next
    End Function
    

    In your Workbook code, you just put the call to the routine that displays the form

    Private Sub Workbook_Open()
        showLoginForm
    End Sub
    

    And in the code of the form, put the following code (adapt it to your program logic and your button names)

    Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
        Application.Visible = True
    End Sub
    
    Private Sub CommandButton1_Click()
        Application.Visible = True
        ThisWorkbook.Windows(1).Visible = True
        ThisWorkbook.Sheets(1).Activate
        Me.Hide
    End Sub
    

    You should add the QueryClose-trigger to make Excel visible in all cases, even if the user closes the form using the red x-button.