Excel 如何忽略使用可选参数的代码?
我有一个sub,它接受一个必选参数和一个可选参数:Excel 如何忽略使用可选参数的代码?,excel,vba,optional-parameters,Excel,Vba,Optional Parameters,我有一个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.Capti
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
Private子命令按钮1\u单击()
'对于标签,请检查是否已通过
如果不是,那么lbl什么都不是
MsgBox“标签控件作为参数传递”
其他的
MsgBox“标签控件未作为参数传递”
如果结束
端接头
谢谢Siddharth Rout!我“分离”了lbl的代码,并按照您的演示对其进行了测试,现在它可以完美地工作:)