Question

The below example the optional arguments must be given in order; hence ShowHeaders Must Precede ValueAdd and so on. If I want to specify ValueAdd, I*must* specify ShowHeaders:

Function Example(Value1, Optional ShowHeaders = "Headers=N", Optional ValueAdd = "Sprd=0")

I want to be able to specify one or more of a (relatively) large list of optional arguments: 1) but not in order, and 2) not necessarily all of them.

For 1) I was thinking, perhaps make a list of arguments generic, eg rather than the above do:

Function Example(Value1, Optional Arg1, Optional Arg2)

Then subsequently check if the leftmost section of Arg1 = "Headers=" or "Sprd=" and so on, and then do the same for Arg2. This is fine but doesn't seem terribly efficient and I'd be planning on creating UDFs with > 10 optional arguments. The above solution would also address 2) but I just don't feel its very good coding.

For 2) I know we can use

If IsMissing(Arg) Then

but this doesn't really address the order we specify functions.

Était-ce utile?

La solution

You can use the := operator along with the name of the variable. This way you only need to send the optional values that are specific to that call. Using your above example you could use:

Call Example(Value1, ValueAdd := "Sprd=0")

And this way you don't have to enter anything about showheaders etc.

Edit:

I've modified your example to handle the missing arguments so that they can be used for maths, hope this helps.

Function Example(Value1, Optional ValueA, Optional ValueB)

    If IsMissing(ValueB) Then ValueB = 0
    If IsMissing(ValueA) Then ValueA = 0

    Example = (Value1 + ValueA) * ValueB)
    MsgBox (Example)

End Function

Sub TestExample()
    Call Example(2, ValueB:=1)
    Call Example(2, ValueB:=1, ValueA:=6)
End Sub
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top