[英]What's the difference between “end” and “exit sub” in VBA?
In VBA, sometimes we want to exit the program after some condition is true.在 VBA 中,有时我们想在某些条件为真后退出程序。 But do I use
end
or exit sub
?但是我是使用
end
还是exit sub
?
This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End
and End Sub
are not the same.这有点超出您的问题范围,但为了避免对 VBA 新手的读者造成任何潜在的混淆:
End
和End Sub
是不一样的。 They don't perform the same task.它们不执行相同的任务。
End
puts a stop to ALL code execution and you should almost always use Exit Sub
(or Exit Function
, respectively). End
停止所有代码执行,您几乎应该总是使用Exit Sub
(或分别为Exit Function
)。
End halts ALL exectution.
End 停止所有执行。 While this sounds tempting to do it also clears all global and static variables.
虽然这听起来很诱人,但它也会清除所有全局和静态变量。 ( source )
(来源)
See also the MSDN dox for the End Statement另请参阅结束声明的 MSDN dox
When executed, the
End
statement resets allmodule-level variables and all static local variables in allmodules.执行时,
End
语句会重置所有模块级变量和所有模块中的所有静态局部变量。 To preserve the value of these variables, use theStop
statement instead.要保留这些变量的值,请改用
Stop
语句。 You can then resume execution while preserving the value of those variables.然后,您可以在保留这些变量的值的同时恢复执行。
Note The
End
statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code.注意
End
语句会突然停止代码执行,而不调用 Unload、QueryUnload 或 Terminate 事件或任何其他 Visual Basic 代码。 Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed.放置在窗体和类模块的 Unload、QueryUnload 和 Terminate 事件中的代码不会执行。 Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed.
从类模块创建的对象将被销毁,使用 Open 语句打开的文件将被关闭,程序使用的内存将被释放。 Object references held by other programs are invalidated.
其他程序持有的对象引用无效。
Nor is End Sub
and Exit Sub
the same. End Sub
和Exit Sub
也不相同。 End Sub
can't be called in the same way Exit Sub
can be, because the compiler doesn't allow it. End Sub
不能像Exit Sub
那样被调用,因为编译器不允许这样做。
This again means you have to Exit Sub
, which is a perfectly legal operation :这再次意味着您必须
Exit Sub
,这是一个完全合法的操作:
Exit Sub
退出子
Immediately exits the Sub procedure in which it appears.立即退出出现它的 Sub 过程。 Execution continues with the statement following the statement that called the Sub procedure.
继续执行调用Sub过程的语句之后的语句。 Exit Sub can be used only inside a Sub procedure.
Exit Sub只能在Sub过程中使用。
Additionally, and once you get the feel for how procedures work, obviously, End Sub
does not clear any global variables.此外,一旦您了解了程序的工作方式,显然
End Sub
不会清除任何全局变量。 But it does clear local (Dim'd) variables :但它确实清除了本地(Dim'd)变量:
End Sub
结束子
Terminates the definition of this procedure .终止此过程的定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.