Excel VBA:编译错误:未find方法或数据成员

编辑:澄清,下面看到的代码是在一个模块内,用户窗体都包含在自己的代码。

我有以下代码。 当我去运行它时,Excel引发了一个编译错误: Method or data member not found并突出显示下面的一段代码: .showInputsDialog 。 我不知道如何解决这个错误。

为了提供更多信息,sub sportUserForm应该调用一个UserForm的sportsUsrFrm 。 任何有关这个问题的帮助,不胜感激。

 Option Explicit Sub sportUserForm() Dim sSport As String, sPreference As String If sportsUsrFrm.showInputsDialog(sSport, sPreference) Then MsgBox "Your favorite sport is " & sSport & ", and you usually " _ & sPreference & "." Else MsgBox "Sorry you don't want to play." End If End Sub Public Function showInputsDialog(sSports As String, sPreference As String) As Boolean Call Initialize Me.Show If Not cancel Then If optBaseball.Value Then sSport = "Baseball" ElseIf optBasketball.Value Then sSport = "Basketball" Elss sSport = "Football" End If If optTV.Value Then sPreference = "watch on TV" _ Else: sPreference = "go to games" End If showInputsDialog = Not cancel Unload Me End Function 

用户代码为sportUsrFrm

 Option Explicit Private Sub cmdCnl_Click() Me.Hide cancel = True End Sub Private Sub cmdOK_Click() If Valid Then Me.Hide cancel = False End Sub 

UserForm图像

你得到的错误是因为showInputsDialog不是表单的成员,它是你调用它的模块的成员。 你也应该得到这两行的编译错误…

 Call Initialize Me.Show 

…因为你似乎正在把模块和表格代码混在一起。

这就是说,你正在过度这个。 用户窗体是一个类模块,它可以存储在一个variables(或在这种情况下,在一个With块),并可以有属性。 我会添加一个Cancelled财产的forms:

 'In sportsUsrFrm Option Explicit Private mCancel As Boolean Public Property Get Cancelled() As Boolean Cancelled = mCancel End Property Private Sub cmdCnl_Click() Me.Hide mCancel = True End Sub Private Sub cmdOK_Click() If Valid Then Me.Hide '<-- You still need to implement `Valid` End Sub 

然后像这样调用它:

 Sub sportUserForm() With New sportsUsrFrm .Show Dim sSport As String, sPreference As String If Not .Cancelled Then If .optBaseball.Value Then sSport = "Baseball" ElseIf .optBasketball.Value Then sSport = "Basketball" Else sSport = "Football" End If If .optTV.Value Then sPreference = "watch on TV" Else sPreference = "go to games" End If MsgBox "Your favorite sport is " & sSport & ", and you usually " _ & sPreference & "." Else MsgBox "Sorry you don't want to play." End If End With End Sub