Home » excel » excel – How to ignore code that uses an optional argument?

excel – How to ignore code that uses an optional argument?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a sub that takes a required argument and an optional one:

Sub selectRange(txtbox As MSForms.TextBox, Optional lbl As MSForms.Label)

I have to pass both arguments or I get an error.

The error is understandable given that the sub contains lines that directly refer to the optional argument (lbl), lines like:

If Len(s) = 0 Then
    lbl.ForeColor = RGB(255, 0, 0)
    lbl.Font.Italic = True
    lbl.Caption = "{!this range doesn't contain values!}"
    Exit Sub
End If

The optional argument is referred to in a number of other places in the code.

What modifications do I make so that selectRange can operate where just the required argument is passed?

How to&Answers:

You need to check if the control is passed and then handle it accordingly. For example

Sub selectRange(txtbox As MSForms.TextBox, Optional lbl As MSForms.Label)
    '
    '~~> Rest of the code which has nothing to do with the label
    '

    '~~> For label, Check it is passed
    If Not lbl Is Nothing Then
        If Len(s) = 0 Then
            lbl.ForeColor = RGB(255, 0, 0)
            lbl.Font.Italic = True
            lbl.Caption = "{!this range doesn't contain values!}"
            Exit Sub
        End If
    End If
End Sub

Here is how you can test it

Private Sub CommandButton1_Click()
    '<~~ This is will give the first message box
    selectRange TextBox1, Label1

    '<~~ This is will give the Second message box
    selectRange TextBox1
End Sub

Sub selectRange(txtbox As MSForms.TextBox, Optional lbl As MSForms.Label)
    '~~> For label, Check it is passed
    If Not lbl Is Nothing Then
        MsgBox "Label control is passed as a parameter"
    Else
        MsgBox "Label control is not passed as a parameter"
    End If
End Sub