学习日志
全民一起VBA提高篇
第六回 GOTO语句不走寻常路,EXIT跳出轮回圈
相关知识点
'exit do ; exit for ; exit sub ; exit function
'exit 只能跳出它所在的那一层循环
'goto 可以跳转到同一过程(函数)内的任意一行
退出循环 exit
Option Explicit
'用逻辑变量控制流程
Sub findfirstdata()
Dim i As Long,found as boolean
i = 3
found = false
Do While not found and Trim(Cells(i, 2)) <> ""
If InStr(Cells(i, 2), "观音") > 0 Then
Range(Cells(i, 1), Cells(i, 2)).Interior.Color = vbYellow
found = true
End If
i = i + 1
Loop
End Sub
'用exit do 退出
Sub findfirstdata()
Dim i As Long
i = 3
Do While Trim(Cells(i, 2)) <> ""
If InStr(Cells(i, 2), "观音") > 0 Then
Range(Cells(i, 1), Cells(i, 2)).Interior.Color = vbYellow
Exit Do
End If
i = i + 1
Loop
End Sub
错误处理 goto
Option Explicit
Sub errortest()
Dim i%
i = Cells(5, 5) '比如 单元格内赋值200
On Error GoTo myerror:
i = i ^ 2
Cells(5, 6) = i
Exit Sub
myerror:
MsgBox "输入数字有点大,小一点试试"
End Sub