Exit Sub does not seem to exit my sub

Lai Kan Leon 596 Reputation points
2021-08-28T12:06:12.133+00:00

Hello,

I am developing a VBA application which I will convert to Excel add-in later (to be used with any Excel workbook).

My Excel application is working correctly. I have a command button in a worksheet. When I click on it, it triggers my UserForm1.

Private Sub CommandButton1_Click()
UserForm1.Show
End Sub

My UsererForm1 has a code called:
Public Sub UserForm_Initialize()

I think that this is the first code that VBA reads. Am I right?


Now, I want my (future) add-in to work only with a given workbook. Rather than validating the name of the Excel workbook, I create a hidden worksheet called "xyz...".

If someone attempts to run my add-in with a workbook that does not contain the secret worksheet, the add-in should exit.


Here is my (pseudo) code (in the UserForm code)

Public Sub UserForm_Initialize()
Dim .....

If sheetExists " xyz...") = False Then
MsgBox "......" 
Exit Sub

Call Sub1, etc....

End Sub

When I run my macro with an appropriate workbook (i.e. does not contain the hidden sheet), the MsgBox is triggered right.

But here is the problem:

Instead of exiting mu application completely, the code continues to run NORMALLY as if I did not put the Exit Sub Line. The Userform pops up and works normally.


Could anybody tell me what is wrong?

Thanks
Leon

Developer technologies Visual Basic for Applications
0 comments No comments
{count} votes

Accepted answer
  1. Lai Kan Leon 596 Reputation points
    2021-08-28T12:16:05.857+00:00

    Hello,

    I found my error

    My Command button should not call the UserForm directly, but should call a sub which calls the UserForm.

    When I put the Exit Sub in the Sub, it works...

    Leon

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.