Browse » Home
Tuesday, August 13, 2013
How to Exit From a Sub in VBA
1. Open the VBA editor. Double-click on one of the Microsoft Office programs that you want work with. Click on the 'Developer' tab and then click on 'Visual Basic.' If you don't see the 'Developer' tab, click on the 'File' tab and then 'Options.' Click on the 'Customize Ribbon' tab in the 'Options' dialog box. Click on 'Main tabs,' and then click on the 'Developer' check box. Click 'OK' to close the 'Options' dialog box.
2. Navigate to the sub procedure that you want to work with in the Visual Basic Editor. Double-click on the page in the right pane to open it. To work on a new procedure, click on 'Insert' and then 'Sub Procedure.'
3. Add the 'Exit Sub' command in the sub procedure where you want to exit a certain block of code. This will be between the Sub and End Sub commands. Usually, the Exit Sub command is added right after the code handler. Here is an example of a code block with an Exit Sub command:'Sub message ()MsgBox 'Hello World!'On Error GoTo Error_Handler:Worksheets('Welcome Message').ActivateExit SubError_Handler:If Err.Number = 9 ThenWorksheets.Add.Name = 'Welcome Message'ResumeEnd IfEnd Sub'The sub procedure shows a message box that says 'Hello World.' If for some reason the program can't display the message, it is directed to the 'Error_Handler' block. To stop the code from continuing to cycle through the same bits of code, the 'Exit Sub' command is given.