question

LaiKanLeon-4557 avatar image
0 Votes"
LaiKanLeon-4557 asked LaiKanLeon-4557 answered

Exit Sub does not seem to exit my sub

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










office-vba-dev
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

LaiKanLeon-4557 avatar image
0 Votes"
LaiKanLeon-4557 answered

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

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.