gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:23:44 26 4
gpt4 key购买 nike

我有一个 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

关于excel - 如何忽略使用可选参数的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60015300/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com