vba 在被调用的子程序中结束宏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18792552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ending a macro within a called subroutine
提问by Richard Pullman
I have a macro (CMOV) which calls another subroutine (CMOV2) that checks for a condition which, if met, displays a vbokaycancel message box which i set equal to a variable called irep,
我有一个宏 (CMOV),它调用另一个子例程 (CMOV2),该子例程检查条件,如果满足,则显示一个 vbokaycancel 消息框,我将其设置为等于名为 irep 的变量,
I want it if someone hits cancel (irep=2) for it to call off the whole macro. That is not only exit CMOV2 but also exit CMOV.
如果有人点击取消(irep = 2),我希望它取消整个宏。这不仅是退出 CMOV2,而且是退出 CMOV。
Currently, I have
目前,我有
If Hymanal(1) <> vbNullString Then
irep = MsgBox("Warning: You have a selection with two swingarms" _
& " that are on the same radius and cannot swing past one another " _
& Chr$(13) & " Choose Okay if you still wish to proceed otherwise " _
& " choose Cancel to revise your order" & Chr$(13) & " " _
& Hymanal(1) & Chr$(13) & " " & Hymanal(2), vbOKCancel)
**If irep = 2 Then
Exit Sub**
Else: End If
Else: End If
End Sub
at the end of the subroutine. The issue is that even though this exits the CMOV2, CMOV continues to run. Is there a way to end this sub, and the one which called it?
在子程序结束时。问题是,即使这退出了 CMOV2,CMOV 继续运行。有没有办法结束这个子,以及调用它的那个?
回答by Cor_Blimey
End
Note that End completely stops code execution (within the current call stack so it doesn't effect other projects like Addins etc (a good thing)) but it will close any open file handles (a good thing). On the other hand, , static and module level variables (if you use them) will lose their values and Class terminate methods won't be run so if you have more of an 'app' than a macro this may not be desired.
请注意, End 完全停止代码执行(在当前调用堆栈内,因此它不会影响其他项目,如 Addins 等(一件好事)),但它会关闭任何打开的文件句柄(一件好事)。另一方面,静态和模块级变量(如果您使用它们)将丢失它们的值并且类终止方法将不会运行,因此如果您有更多的“应用程序”而不是宏,这可能是不需要的。
It sounds like for your purposes this is ok and is probably the simplest way to go about it.
对于您的目的来说,这听起来没问题,并且可能是最简单的方法。
A silly example:
一个愚蠢的例子:
Sub foo()
Dim i As Long
For i = 0 To 10
If i = 2 Then
Debug.Print "hooray"
End
Else
Debug.Print "hip"
End If
Next i
End Sub
回答by Siddharth Rout
Declare a Boolean variable at the top and set it to True
if the user presses cancel. Here is an example.
在顶部声明一个布尔变量并将其设置为True
如果用户按下取消。这是一个例子。
Dim ExitAll As Boolean
Sub CMOV()
'
'~~> Rest of the code
'
ExitAll = False
CMOV2
If ExitAll = True Then Exit Sub
MsgBox "Hello World"
'
'~~> Rest of the code
'
End Sub
Sub CMOV2()
'
'~~> Rest of the code
'
If Hymanal(1) <> vbNullString Then
irep = MsgBox("Some Message", vbOKCancel)
If irep = 2 Then
ExitAll = True
Exit Sub
End If
End If
'
'~~> Rest of the code
'
End Sub