VBA入门到进阶常用知识代码总结08

第8集 VBA分支与End语句
21、 End和Exit
End跳出窗体代码的同时,关闭窗体;Exit跳出的一般为过程本身,不关闭窗体。Exit Sub、Exit Function、Exit For、Exit Do。
22、 分支语句

  1. Goto:跳转到指定标签处。
    'Goto语句,跳转到指定的地方
    Sub t1()
    Dim x As Integer
    Dim sr
    100:
    sr = Application.InputBox(“请输入数字”, “输入提示”)
    If Len(sr) = 0 Then GoTo 100
    End Sub
  2. GoSub……Return:跳到指定标签处,再跳回到原处,执行后续语句。
    'gosub…return ,跳过去,再跳回来
    Sub t2()
    Dim x As Integer
    For x = 1 To 10
    If Cells(x, 1) Mod 2 = 0 Then GoSub 100
    Next x
    Exit Sub
    100:
    Cells(x, 1) = “偶数”
    Return
    End Sub
  3. On Error Resume Next:忽略当前错误,执行下一条语句。resume:继续
    'on error resume next '遇到错误,跳过继续执行下一句
    Sub t3()
    On Error Resume Next
    Dim x As Integer
    For x = 1 To 10
    Cells(x, 3) = Cells(x, 2) * Cells(x, 1)
    Next x
    End Sub
  4. On Error Goto:出错跳转到指定标签处。
    'on error goto '出错时跳到指定的行数
    Sub t4()
    On Error GoTo 100
    Dim x As Integer
    For x = 1 To 10
    Cells(x, 3) = Cells(x, 2) * Cells(x, 1)
    Next x
    Exit Sub
    100:
    MsgBox “在第” & x & “行出错了”
    End Sub
  5. On Error GoTo 0:取消On Error Resume Next的作用。
    'on error goto 0 '取消错误跳转
    Sub t5()
    On Error Resume Next
    Dim x As Integer
    For x = 1 To 10
    If x > 5 Then On Error GoTo 0
    Cells(x, 3) = Cells(x, 2) * Cells(x, 1)
    Next x
    Exit Sub
    End Sub
发布了47 篇原创文章 · 获赞 0 · 访问量 249

猜你喜欢

转载自blog.csdn.net/tiansdk320/article/details/104325639