VBA 暂停代码并等待用户交互

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25287259/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:13:31  来源:igfitidea点击:

VBA Pause code and wait for user interaction

vbaexcel-vbaexcel

提问by art123456

I have code where I have added an error box that pops up based on certain conditions. The conditions are:

我有代码,其中添加了一个基于某些条件弹出的错误框。条件是:

If Range (Q2:Q) = "" Then
ErrorFrame.Visible = True

When the error frame pops up, there are two options I want that I have added buttons for:

当错误框弹出时,我希望为以下两个选项添加按钮:

  1. Continue: Continue will continue with the macro regardless if there is data in column Q

  2. Stop: Stop will end the macro so the user can input the data into column Q and rerun the macro

  1. 继续:无论 Q 列是否有数据,Continue 都将继续执行宏

  2. 停止:停止将结束宏,以便用户可以将数据输入到 Q 列并重新运行宏

I also would like it so that when the error frame pops up, the code is paused and does not continue yet until the user chooses one of the options.

我也希望这样,当错误帧弹出时,代码会暂停并且不会继续,直到用户选择其中一个选项。

Would anyone be able to give me an example of how this could work? I'm having trouble thinking of how to write this. Any help is much appreciated, thanks!

谁能给我一个例子来说明这是如何工作的?我很难想到如何写这个。非常感谢任何帮助,谢谢!

回答by art123456

Figured it out myself:

自己想出来的:

If WorksheetFunction.CountA(Range("Q:Q")) = 0 Then
UserForm1.ErrorFrame.Visible = True
    Do While UserForm1.ErrorFrame.Visible = True
    DoEvents
    Loop
    If ContinueFlag = True Then GoTo Line1
End If

Line1:

Basically for the continue button I just added a flag on it so when clicked it would make the flag true. Then in the function as you can see, when the flag is true it will go to Line 1, which then continues the code and exits the Do Whileloop.

基本上,对于继续按钮,我只是在其上添加了一个标志,因此单击它会使标志为真。然后在函数中,如您所见,当标志为真时,它将转到第 1 行,然后继续执行代码并退出Do While循环。

May not be the most efficient way, I'm sure, but let me know what you guys think and if there is a better way to do it.

我敢肯定,这可能不是最有效的方法,但请告诉我你们的想法以及是否有更好的方法。