0

I'm using Excel Version 1902, Build 11328.20392 within MS Office 365 ProPlus.

I call a function from a cell in a worksheet:

=addOnlyPositiveValues(D2, E2, F2,G2)

Only the first parameter is mandatory, the others are optional:

Function addOnlyPositiveValues(v01 As Range, Optional v02 As Range, Optional v03 As Range, Optional v04 As Range, Optional v05 As Range ) As Double
    Dim dblRet                  As Double
    dblRet = 0
    dblRet = var2dbl_positiveOnly(v01.Value)
    If Not (IsMissing(v02)) Then dblRet = dblRet + var2dbl_positiveOnly(CVar(v02.Value))
    If Not (IsMissing(v03)) Then dblRet = dblRet + var2dbl_positiveOnly(CVar(v03.Value))
    If Not (IsMissing(v04)) Then dblRet = dblRet + var2dbl_positiveOnly(CVar(v04.Value))
    If Not (IsMissing(v05)) Then dblRet = dblRet + var2dbl_positiveOnly(CVar(v05.Value))

'    If Not (IsMissing(v05) Or (v05 Is Nothing)) Then dblRet = dblRet + var2dbl_positiveOnly(CVar(v05.Value))

    addOnlyPositiveValues = dblRet
End Function

This worked until recently (can't tell exactly when it starting to act up).
In my example above I don't set a 5th parameter.
I expect the function to skip the If Not (IsMissing(v05)) Then .... Stepping through the code I see that v05 is NOTHING.

My workaround:

If Not (IsMissing(v05) Or (v05 Is Nothing)) Then ...
Community
  • 1
  • 1
Joe Phi
  • 340
  • 1
  • 4
  • 14
  • In case you want to look into another option for your function with unsure number of parameters: the ParamArray is a nice option. – Jochen Feb 12 '20 at 09:56

1 Answers1

5

Optional parameters only make sense when they are declared as Variant. Only a Variant can contain the special value Variant/Missing that the IsMissing function detects.

Your parameters are Ranges, so when not filled in, they contain Nothing, and IsMissing is always going to be False for them.

That code could never work with IsMissing. If it did, then the parameters were declared as Variant, either explicitly (As Variant) or implicitly (by omitting the type completely).

GSerg
  • 76,472
  • 17
  • 159
  • 346
  • very good explanation! I had the parameters expl. declared as variants once but it didn't work anymore from one day to the other, stalling the whole application. I have no clue why that was but tracing lead to the workaround with ranges and 'Is Nothing'. I fell back to variants now and it works just fine. – Joe Phi Nov 14 '19 at 11:32