VBA/Excel/Access/Word/Language Basics/GoTo

Материал из VB Эксперт
Перейти к: навигация, поиск

A GoTo statement with a condition

 
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



A line number is simply a number placed at the beginning of a line to identify it. For example, consider this demonstration of GoTo:

 
Sub Demo_of_GoTo()
1
    If MsgBox("Go to line 1?", vbYesNo) = vbYes Then
        GoTo 1
    End If
End Sub



how a GoTo statement works:

 
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



Use GoTo to do a loop

 
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