仍然暂停代码执行的无模式形式 [英] Modeless form that still pauses code execution
问题描述
是否有一个用户窗体可以无模式运行,同时仍像模式窗体一样暂停代码执行?
Is there anyway to have a userform that acts modeless, while still pausing code execution like a modal form?
我希望显示用户窗体,但仍允许与父程序交互.模态表单阻止与父程序的交互.无模式表单可以工作,但我希望代码执行在表单启动时暂停.
I'd like the userform to show, but still allow interaction with the parent program. Modal forms block interaction with the parent program. A modeless form would work, but I would like the code execution to pause while the form is up.
我已经通过创建一个检查表单是否可见的无限循环来解决这个问题,但这似乎有点 hacky.
I've worked around this by creating an infinite loop that checks if the form is visible, but that seems a bit hacky.
Public Sub GetFormInfoAndDoStuff
ufForm.show vbModeless
Do while ufForm.Visible
DoEvents
Loop
' Do other stuff dependent on form
End Sub
编辑澄清 .show 之后的代码必须在用户表单完成后执行
推荐答案
您应该能够将表单显示为 vbModeless
并且仅在特别请求时执行代码,即从 CommandButton
或其他控件.
You should be able display the form as vbModeless
and only execute code when specifically requested, i.e., from a CommandButton
or other control.
然后,您可以通过X"按钮或通过另一个调用 UserForm_Terminate
事件的控件将表单保持可见/显示,直到它被特别关闭.
You then leave the form visible/shown until it is specifically closed, via the "X" button or via another control which calls the UserForm_Terminate
event.
为了实现这一点,您可能需要将一些可执行代码移动到另一个子例程和/或模块中,并从 CommandButton_Click
事件中调用此子例程.
In order to achieve this, you may need to move some of your executable code in to another subroutine and/or module, and call this subroutine for example from a CommandButton_Click
event.
您已经在某处有一个子例程,其中包含如下行:
You already have a subroutine somewhere that contains a line like:
Sub ShowTheForm()
UserForm1.Show vbModeless
End Sub
因此表单可以正确显示以允许用户向父应用程序输入.
So the form is displayed properly to allow user-input to the parent application.
您实际上不需要在上述模块中添加任何其他代码.我们会将其他代码放在其他模块/子程序中,然后从命令按钮等用户控件中调用它.
You don't really need to put any other code in the above module. We will put the other code in other modules/subs, and then call it from user controls like command buttons.
示例:
获取所有可执行代码,并将其放入另一个子程序(如果它适合您的组织偏好,另一个模块),例如:
Take all of your executable code, and put it in another subroutine (and if it suits your organizational preference, another module), like:
Sub MyMacro(msg$)
MsgBox msg
End Sub
在用户窗体上,添加一个命令按钮并为其分配以下代码:
On the UserForm, add a command button and assign it the following code:
Sub CommandButton1_Click()
MyMacro "hello"
End Sub
现在,表单将一直显示,直到用户单击X"按钮.代码只会在从命令按钮调用时运行.
Now, the form will display until the user clicks the "X" button. Code will only run when called from the command button.
编辑澄清
您无需使用此方法暂停"执行.一旦表单无模式显示,执行就会结束,并且表单仍然存在.该对象具有一些事件,您可以使用这些事件来触发代码的进一步执行.
You don't need to "pause" the execution using this method. Execution ends once the form is displayed modelessly, and the form persists. The object has some events which you may use to trigger further execution of code.
这篇关于仍然暂停代码执行的无模式形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!