gpt4 book ai didi

excel - VBA中 "end"和 "exit sub"有什么区别?

转载 作者:行者123 更新时间:2023-12-01 16:59:47 24 4
gpt4 key购买 nike

在VBA中,有时我们想在某些条件成立后退出程序。但我应该使用 end 还是 exit sub 呢?

最佳答案

这有点超出了您的问题范围,但为了避免刚接触 VBA 的读者产生任何潜在的困惑:EndEnd Sub 并不相同。他们不执行相同的任务。

End 会停止所有代码执行,您几乎应该始终使用 Exit Sub (或分别使用 Exit Function)。

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

另请参阅 MSDN dox 的 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.

End SubExit Sub 也不一样。 End Sub 不能以与 Exit Sub 相同的方式调用,因为编译器不允许这样做。

enter image description here

这再次意味着您必须Exit Sub,即 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.

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

End Sub
Terminates the definition of this procedure.

关于excel - VBA中 "end"和 "exit sub"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36491908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com