Search code examples
vb6subroutineoptional-parameters

Elegant way to pass as an optional parameter to make the subroutine work as if it was omitted?


In VB6, the function Mid(string, start, [length]) has an optional parameter length. If omitted, the whole characters after the start bound will be passed.

Say I want this default behaviour only in a certain condition:

s = Mid(s, i, IIf(condition, j, TheValue)) ' What could be TheValue?

Since length is of Variant type, I tried Empty. It didn't work. Neither did -1 and Nothing. I didn't want to duplicate to Mid call in an If-Then-Else clause or somehow else. Is this possible?


Solution

  • Here is a working sample with OP's s = Mid(s, i, IIf(condition, j, TheValue)) line

    Option Explicit
    
    Property Get TheValue(Optional RetVal As Variant)
        TheValue = RetVal
    End Property
    
    Private Sub Form_Load()
        Dim s As String
        Dim i As Long
        Dim j As Long
        Dim condition As Boolean
        
        s = "test test test"
        i = 6: j = 3
        condition = False
        s = Mid(s, i, IIf(condition, j, TheValue))         '<--- this works!
        Debug.Print s
    End Sub
    

    Notice how TheValue returns a "missing" Variant i.e. one which tests positive for IsMissing and can be used in place of optional parameters instead of not passing actual argument.