VBA ByRef 参数类型不匹配

VBA ByRef argument type mismatch

最初在我的主要代码部分,我有一个丑陋的 if 语句 - 尽管它会丑陋 运行。我决定让它成为一个我会调用的函数,这导致我得到一个错误“编译错误:ByRef 参数类型不匹配”。我的假设是该函数需要被正确引用,尽管我一直在阅读文档并且不明白为什么 >.<

正在声明 ShiftValue 变量: 将 ShiftValue 调暗为字符串 <br> ShiftValue = LCase(Sheets("Raw_Rota").Cells(Counter, "C").Value)

函数内容及声明:

Function ShiftCompare(ByRef ShiftValue As String)

If StrComp(ShiftValue, "am", vbTextCompare) = 0 Then
        Call IncAMs(AMs)   'this function increments the variable by 1.
        Call Inc(Counter)

    ElseIf StrComp(ShiftValue, "pm", vbTextCompare) = 0 Then
        Call IncPMs(PMs)
        Call Inc(Counter)

    ElseIf StrComp(ShiftValue, "days", vbTextCompare) = 0 Then
        Call IncDays(Days)
        Call Inc(Counter)

    ElseIf StrComp(ShiftValue, "leave", vbTextCompare) = 0 Then
        Call IncLeave(Leave)
        Call Inc(Counter)

    Else 'If the string doesn't compare to the above values tally it as unknown
        Call IncUnknown(Unknown)
        Call Inc(Counter)
    End If
End Function

更新:

我的函数调用在 If 部分的 Else 部分,如下所示:

If X
"'Do stuff..."

Else 

Call ShiftCompare(ShiftValue)

EndIf

函数行上出现错误:

Function ShiftCompare(ByVal ShiftValue As String)

引用的任何单元格中的值为空或字符串。

调用函数时参数的值不是字符串。检查 ShiftValue 的值并重试。如果你想确保它是一个字符串,像这样传递它 Call ShiftCompare("MyStringValue")


函数的想法是 return 是一个值是很好的。 你的没有 return。将 Function 更改为 Sub

除了上面 Vityata 的回答之外,考虑一个 Select 语句来避免所有这些 ElseIf 语句。它运行得更快。

Option Compare Text
Public Sub ShiftCompare(ByVal ShiftValue As String)
    Select Case True
        Case StrComp(ShiftValue, "am") = 0:
            Call IncAMs(AMs)   'this function increments the variable by 1.
            Call Inc(Counter)

        Case StrComp(ShiftValue, "pm") = 0:
            Call IncPMs(PMs)
            Call Inc(Counter)

        Case StrComp(ShiftValue, "days") = 0:
            Call IncDays(Days)
            Call Inc(Counter)

        Case StrComp(ShiftValue, "leave") = 0:
            Call IncLeave(Leave)
            Call Inc(Counter)

        Case Else:  'If the string doesn't compare to the above values tally it as unknown
            Call IncUnknown(Unknown)
            Call Inc(Counter)
    End Select
End Sub