VBA ByRef argument type mismatch

北战南征 提交于 2019-12-10 21:42:12

问题


Initially in my main code section I had an ugly if statement - though ugly it would run. I decided to make it a function that I would call, this caused me to get an error "Compile error: ByRef argument type mismatch". My assumption is that the function needs to be referenced properly, though I've been reading the documentation and can't see why >.<

Declaring ShiftValue variable: Dim ShiftValue As String
ShiftValue = LCase(Sheets("Raw_Rota").Cells(Counter, "C").Value)

The function contents and declaration:

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

Update:

My function call is in the Else part of an If section like so:

If X
"'Do stuff..."

Else 

Call ShiftCompare(ShiftValue)

EndIf

The error is raised on the Function line:

Function ShiftCompare(ByVal ShiftValue As String)

The value in whatever cell being referenced is either empty or a string.


回答1:


The value of the parameter when you are calling the function is not a string. Check the value of ShiftValue and try again. If you want to make sure it is a string, pass it like this Call ShiftCompare("MyStringValue")


The idea of the Function is that it is good that it returns a value. Yours does not return. Change Function to Sub.




回答2:


In addition to Vityata's answer above, consider a Select statement to avoid all those ElseIf statements. It runs faster.

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


来源:https://stackoverflow.com/questions/46239566/vba-byref-argument-type-mismatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!