VBA调用一个用户窗体中的子程序来自另一个用户窗体

3
我正在使用Excel VBA。我有两个用户窗体: 客户信息(ClientInfo)和客户搜索(ClientSearch)
在ClientSearch中,我通过搜索Excel工作表来列出所有具有相同姓氏的客户。然后,我选择要查看的客户(通过在列表中突出显示名称并单击命令按钮cmdOpenClientInfo),并确定他们的客户ID(也在工作表中)。 然后,我想将此客户ID传递到ClientInfo窗体,以便使用工作表中的相关数据填充该窗体上的所有文本框:
在ClientSearch窗体中编码:
Private Sub cmdOpenClientInfo_Click()

 Dim ClientID As Integer

 ClientID = textSrchClientID.value

'user msgbox to check to make sure I get the correct ClientID ... and I do

 msgbox(ClientID)

 Me.Hide

 frmClientInfo.show

Call frmClientInfo.PopulateClientInfo(ClientID)  'this is where it fails

End Sub

在ClientInfo表单中编写的代码:

Sub PopulateClientInfo(ClientID As Integer)

  'this is where I would populate the text field

End Sub

例程总是卡在 CALL frmClientInfo.PopulateClientInfo(ClientID) 处。
在上述情况下,我得到了运行时错误“424”对象所需。
我尝试了这个论坛中提出的各种解决方案,但没有找到解决方案。
2个回答

1

您对frmClientInfo.show的调用处于模态模式,因此在新窗体关闭之前,下一条语句不会执行。您可以尝试将调用设置为非模态:

frmClientInfo.show Modal:=False

但这可能会导致其他问题的产生。最好保持模态模式工作,但在表单显示之前将ClientID参数传递给表单。
1- 将frmClientInfoPopulateClientInfo方法修改为以下内容:
Public Sub PopulateClientInfo(ClientID As Integer)
    '....
    'populate The fields, then:
    '....
    Me.Show ' <-- form shows itself after populating its fields
End Sub

2- 在ClientSearch表单中删除对frmClientInfo.show的调用。


我尝试了你的建议,但不幸的是,我仍然遇到相同的“424”错误。 - Jane
@Jane,你是否使用了Option Explicit?如果没有,我相信如果你设置它,我们将会得到更好的关于错误的信息。 - A.S.H

1

您不能从模块外部调用表单模块中的过程。请尝试以下代码(抱歉,我没有)。

Private Sub cmdOpenClientInfo_Click()

    Dim ClientID As Integer
    Dim FrmInfo As frmClientInfo

    ClientID = textSrchClientID.Value

    'user msgbox to check to make sure I get the correct ClientID ... and I do

    MsgBox (ClientID)

    Me.Hide

    Set FrmInfo = New frmClientInfo
    With FrmInfo
        .Tag = ClientID
        .Show

        ' make this call in the FrmInfo Activate event procedure
        ' PopulateClientInfo(cint(Me.Tag)
    End With
    Unload FrmInfo
    Set FrmInfo = Nothing
End Sub

我假设你有一个名为frmClientInfo的表单。您可以使用命令Set FrmInfo = New frmClientInfo创建该表单的实例。在调用Show方法之前,此对象将不会显示,但您可以访问其所有控件。要将变量传递到该表单,您可以访问其中任何一个控件。也许您有一个Tbx应该显示ClientID。您可以访问该Tbx并设置其值。上面的代码将ClientID分配给表单本身的Tag属性。

当调用Show方法时,表单的Activate事件将发生。那就是运行PopulateClientInfo过程的时刻(当然是在frmClientInfo模块内),从Tag属性中检索ClientId。

请记住,当关闭ClientInfo表单时,代码将继续在cmdOpenClientInfo_Click过程中运行。因此,这是从内存中删除该表单的时间,在另一方面,“FrmInfo”对象仍然存在,您可以从中选择任何您想在调用的表单中使用的信息。语法非常简单,例如:FrmInfo.Textbox1.Value


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接