如何忽略使用可选参数的代码?

How to ignore code that uses an optional argument?

我有一个带有必需参数和可选参数的 sub:

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

我必须传递 两个 个参数,否则会出现错误。

这个错误是可以理解的,因为 sub 包含直接引用可选参数 (lbl) 的行,例如:

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

代码中的许多其他地方都引用了可选参数。

我做了哪些修改,以便 selectRange 可以在只传递所需参数的地方运行?

您需要检查控件是否通过,然后进行相应的处理。例如

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

这里是你如何测试它

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