美文网首页零基础自学VBA
VBA第八讲 分支与END语句

VBA第八讲 分支与END语句

作者: 肉丸子豆 | 来源:发表于2017-04-06 16:37 被阅读10次

     end 语句与exit语句,end语句强制退出所有正在运行的程序。exit是退出指定的语句

    exit sub

    exit function

    exit for例子

    Sub de13()

    Dim x As Integer

    For x = 1 To 100

    Cells(1, 1) = x

    If x = 5 Then

    Exit For

    End If

    Next x

    Range("b1") = 100

    End Sub

    exit do

    分支语句(option explicit)

    goto 语句,跳转到指定的地方

    Sub t1()

    Dim x As Integer

    Dim sr

    100:

    sr = Application.InputBox("enter number", "enter password")

    If Len(sr) = 0 Or Len(sr) = 5 Then GoTo 100

    End Sub

    一个很好玩的地方是,我第一次自己尝试的时候,dim sr as string, 这样运行起来的结果是一个死循环,不断弹出小窗口而且不能被关掉。现在看来原因是,string本身就是五个词,这样会永远跳转到goto语句。暂时原因放在这里,后续有新理解再补充。

    gosub.return 跳过去再跳回来

    Sub t2()

    Dim x As Integer

    For x = 1 To 12

    If Cells(x, 1) Mod 2 = 0 Then GoSub 100

    Next x

    Exit Sub (这一步用exit sub,因为不需要运行底下的100:)

    100:

    Cells(x, 1) = "偶数"

    Return

    End Sub

    on error resume next 遇到错误,跳过继续执行下一句

    Sub t3()

    On Error Resume Next

    Dim x As Integer

    For x = 1 To 11

    Cells(x, 3) = Cells(x, 2) * Cells(x, 1)

    Next x

    End Sub

    出错跳到指定行数 on error goto

    Sub t4()

    On Error GoTo 100

    Dim x As Integer

    For x = 1 To 11

    Cells(x, 3) = Cells(x, 2) * Cells(x, 1)

    Next x

    Exit Sub

    100:

    MsgBox "在第" & x & "行出现错误"

    End Sub

    取消错误跳转 on error goto 0

    Sub t5()

    On Error Resume Next

    Dim x As Integer

    For x = 1 To 11

    If x > 5 Then On Error GoTo 0

    Cells(x, 3) = Cells(x, 2) * Cells(x, 1)

    Next x

    Exit Sub

    End Sub

    相关文章

      网友评论

        本文标题:VBA第八讲 分支与END语句

        本文链接:https://www.haomeiwen.com/subject/lxdaottx.html