How to use the GOTO statement [VBA]
The image above demonstrates the GoTo statement. It "jumps" or "navigates" to another place in the code, in this case, "Start".
VBA code
Sub HowToGoTo() a = 1 Start: MsgBox Range("B2:B4").Cells(a) If a = 3 Then Exit Sub a = a + 1 GoTo Start End Sub
Explaining subroutine
- The subroutine begins with variable a setting it equal to 3.
- Start: is a label which the GoTo statement use in order to know where to "jump".
- The message box appears and shows the value in cell range B2:B4 based on what variable a contains.
- The IF THEN statement checks if variable a is equal to 3 and exits the subroutine if the condition is met.
- Variable a is added with number 1.
- The GoTo statement makes the code "jump" to label "Start:"
- The subroutine is repeated until a is equal to 3.
The GoTo statement is mostly used in error handling techniques. I recommend using For Next, Do While or Do Loop since they make your code easier to follow and understand.
Excel categories
One Response to “How to use the GOTO statement [VBA]”
Leave a Reply
How to comment
How to add a formula to your comment
<code>Insert your formula here.</code>
Convert less than and larger than signs
Use html character entities instead of less than and larger than signs.
< becomes < and > becomes >
How to add VBA code to your comment
[vb 1="vbnet" language=","]
Put your VBA code here.
[/vb]
How to add a picture to your comment:
Upload picture to postimage.org or imgur
Paste image link to your comment.
how to use nonconsecutive rows for listbox
Thank you