调用函数时编译错误

Compile error when calling function

每当我尝试运行我的 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

您没有为 cStatus 函数分配 return 值,因此 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

或者,如果您不需要 return 一个值,您可以将 cStatus 设为 Sub

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

作为旁注,none 的参数是键入的,因此它们将全部作为 Variant 通过 通过引用 ByRef).我不确定这是不是有意为之,但最好还是输入它们,因为大多数时候你会希望按值传递它们 (ByVal)。

例如:

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