Excel VBA:编译错误:找不到方法或数据成员

时间:2016-10-25 22:56:26

标签: excel vba excel-vba compiler-errors

编辑:为了澄清,下面看到的代码在一个模块中,UserForm都包含在自己的代码中。

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

要提供更多信息,子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

的UserForm代码
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 image

1 个答案:

答案 0 :(得分:1)

您收到错误是因为showInputsDialog不是表单的成员,它是您从中调用它的模块的成员。您还应该在这两行上遇到编译错误......

Call Initialize
Me.Show

...因为你似乎把模块和表单代码搞混了。

那就是说,你是在思考这个问题。 UserForm是一个类模块,它可以存储在变量中(或者在这种情况下,存储在With块中),并且可以具有属性。我将Cancelled属性添加到表单中:

'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