VBA/Excel/Access/Word/Language Basics/GoTo
Содержание
A GoTo statement with a condition
<source lang="vb">
Sub gotoDemo()
Dim Response As Integer Response = MsgBox("Do you want to create a daily report for " & _ "the head office from the current document?", _ vbYesNo + vbQuestion, "Create Daily Report") If Response = vbNo Then GoTo Bye
Bye: End Sub
</source>
A line number is simply a number placed at the beginning of a line to identify it. For example, consider this demonstration of GoTo:
<source lang="vb">
Sub Demo_of_GoTo() 1
If MsgBox("Go to line 1?", vbYesNo) = vbYes Then GoTo 1 End If
End Sub
</source>
how a GoTo statement works:
<source lang="vb">
Sub GoToDemo()
userName = InputBox("Enter Your Name: ") If userName <> "123" Then GoTo WrongName MsgBox ("Welcome Bill...")
" ...[More code here] ...
Exit Sub
WrongName:
MsgBox "Sorry."
End Sub
</source>
Use GoTo to do a loop
<source lang="vb">
Sub BadLoop()
Dim StartVal As Long Dim NumToFill As Long Dim CellCount As Long StartVal = InputBox("Enter the starting value: ") NumToFill = InputBox("How many cells? ") ActiveCell = StartVal CellCount = 1
DoAnother:
ActiveCell.Offset(CellCount, 0) = StartVal + CellCount CellCount = CellCount + 1 If CellCount < NumToFill Then GoTo DoAnother _ Else Exit Sub
End Sub
</source>