“结束”之间的区别是什么?和“退出子”在VBA? [英] What's the deference between "end" and "exit sub" in VBA?

查看:234
本文介绍了“结束”之间的区别是什么?和“退出子”在VBA?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在VBA中,有时我们希望在某些条件成立后退出程序。但是我使用 end exit sub

解决方案

这不在你的问题范围之内,但是为了避免对新一代VBA的读者造成任何潜在的混淆: End End Sub 不一样。他们不执行相同的任务。



结束停止所有代码执行,你几乎总是使用 Exit Sub (或 Exit Function )。


结束停止所有exectution。虽然这听起来很诱人,但它也清除
所有全局变量和静态变量。 (



这再次意味着你必须退出子,这是一个完全合法的操作


退出子

立即退出子它出现的程序。
执行继续执行语句后,
称为 Sub 过程。 退出子只能在
过程中使用。


此外,一旦您了解程序的工作原理,显然, End Sub 不清除任何全局变量。但它确实清除本地(Dim'd)变量


结束子

终止此过程的定义。



In VBA, sometimes we want to exit the program after some condition is true. But do I use end or 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. 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 halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. 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. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

这篇关于“结束”之间的区别是什么?和“退出子”在VBA?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆