我有一个带必选参数和可选参数的子:
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可以在仅传递所需参数的地方运行?
您需要检查控件是否通过,然后进行相应处理。例如
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