Adding Control Statements

You place labels within the code of a procedure to mark the subprocedure code. Other than signalling to the GoTo statement the location of the code to run, Excel ignores the label. Labeling the code does not change how it executes. Code within a loop or conditional statement executes only when a condition is met. Labeled code executes when the GoTo statement jumps to it, or when control passes to that area of the code.

If you have multiple areas of labeled code you may not want it all to execute. To avoid execution of code that follows a labeled section, you can either use another GoTo statement or an Exit Sub statement to terminate the current subroutine.

The following example uses the Exit Sub command before the label subprocedure to avoid execution of the T =50 statement. If the GoTo command jumps to the IncreaseValue labeled subprocedure, the T = T * 5 statement does not execute.

Example:

If T < 5 Then GoTo IncreaseValue

Exit Sub

IncreaseValue:

End Sub

Premium Vba Controls For Developer

■ The appropriate GoTo statement executes.

0 Type Label followed by a colon (:); replacing Label with the name you typed in step 3.

'—0 Type statements to execute when label is called.

□ Type Exit Sub to exit procedure after running statements.

0 Switch to Excel and run the macro.

■ The appropriate GoTo statement executes.

0 0

Post a comment