调用函数时编译错误

时间:2015-01-08 16:41:33

标签: vba

每当我尝试运行VBA代码时,我都会收到以下错误Compile Error: Expected =。造成这种情况的原因是什么?

Function cStatus(cValue, mName)
If mName= True Then
rTotal = rTotal + cValue
ElseIf mName= False Then
rTotal = rTotal - cValue
End If
End Function

Private Sub BE_Click()
checkStatus = cStatus(10, "B_E")
End Sub

1 个答案:

答案 0 :(得分:2)

您没有为cStatus函数指定返回值,因此行checkStatus = cStatus(10, "B_E")不知道它正在接收什么。

' Define a return type for the function (I used string).
Function cStatus(cValue, mName) As String
    ' Wrapping True and False in quotes since you are passing a string.
    ' If this is supposed to be a boolean, then type the parameter (see below).
    If mName = "True" Then
        rTotal = rTotal + cValue
    ElseIf mName = "False" Then
        rTotal = rTotal - cValue
    End If

    ' Assign a return value.
    cStatus = "the value"
End Function

或者,如果您不需要返回值,则可以cStatusSub

Sub cStatus(cValue, mName)
    If mName = "True" Then
        rTotal = rTotal + cValue
    ElseIf mName = "False" Then
        rTotal = rTotal - cValue
    End If
End Function

Private Sub BE_Click()
    ' No "checkStatus" variable.

    cStatus 10, "B_E"
End Sub

作为旁注,我们没有输入任何参数,因此它们都会在Variant通过引用传递ByRef)时进入。我不确定这是否有意,但最好输入它们,无论大多数时候你都希望按值(ByVal)传递它们。

例如:

Function cStatus(ByVal cValue As Integer, ByVal mName As Boolean) As String