excel VBA -从用户窗体返回到宏

6rqinv9w  于 2023-03-13  发布在  其他
关注(0)|答案(2)|浏览(221)

我有一个宏,在某个部分显示了一个用户窗体,我公开调暗了用户窗体中的一些变量,以便在主宏中使用它。
现在我想在点击“继续!”命令按钮后回到主宏。
Batch Divider
下面是我的主要宏:

Public C1 As String, C2 As String, C3 As String, C4 As String, C5 As String, C6 As String, C7 As String, C8 As String, C9 As String, C10 As String, C11 As String, C12 As String, C13 As String
Public NumB As Integer, NumofLines As Integer, Q1 As Integer, Q2 As Integer, Q3 As Integer, Q4 As Integer
Public Total As Double, Batch1Total As Double, Batch2Total As Double, Batch3Total As Double, Batch4Total As Double, Batch5Total As Double

Sub priority_calculation()

*Some code ....*

BatchDivider.Show

*Want to continue after hitting Proceed! commandbutton*

End Sub
egmofgnx

egmofgnx1#

调用窗体:

Sub Tester()
    Dim frm As New BatchDivider 'create an instance of the form
    
    frm.Show       'show the form instance: code stop here until form is hidden/unloaded
    Debug.Print frm.MyGlobal    'read the global from the (now hidden) form instance
    Unload frm    'now done with the form....
End Sub

其形式为:

Public MyGlobal As String

Private Sub CommandButton1_Click()
    MyGlobal = "value from form"
    Me.Hide   'not unload
End Sub
krcsximq

krcsximq2#

主要有两种方法。在这两种情况下,都要确保窗体属性ShowModal设置为False。

基于事件

在表单代码中,添加一个事件

Public Event Proceed()

在继续按钮事件处理程序中,添加如下内容:

Private Sub btnProceed_Click()
    RaiseEvent Proceed
End Sub

在您的调用代码中(这需要进行大量的重组,并且也在类模块中),将表单声明为一个对象 * 和事件 *:

Dim WithEvents BatchDivider As BatchDividerForm

单击“继续”时,将激发事件处理程序:

Private Sub BatchDivider_Proceed()
    MsgBox "Proceed"
End Sub

这不会给予你想要的东西--在代码中一个接一个地继续--但是它会给你一种以结构化的方式在代码的各个部分之间进行通信的方法。

轮询

这是一种更容易(也更丑陋)的方法。
在表单代码中添加以下内容:

Private m_Ready As Boolean

Private Sub btnProceed_Click()
    m_Ready = True
End Sub

Property Let IsReady(IsReady As Boolean)
    m_Ready = IsReady
End Property

Property Get IsReady() As Boolean
    IsReady = m_Ready
End Property

在调用代码中,执行如下操作:

Dim BatchDivider As BatchDividerForm
Set BatchDivider = New BatchDividerForm

BatchDivider.IsReady = False
BatchDivider.Show

Do While Not BatchDivider.IsReady
    DoEvents
Loop

MsgBox "Let's proceed"

简而言之,这将向窗体添加一个属性,该属性之前设置为False。在窗体显示后,它将测试该属性是否设置为True。

相关问题