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

问题描述 投票:1回答:1

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

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

我必须传递both参数,否则会出错。

错误是可以理解的,因为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可以在仅传递所需参数的地方运行?

excel vba optional-parameters
1个回答
2
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.