如果是 Variant 类型的参数,可以用 IsMissing() 判断 Option ExplicitSub Main() Test Test True Test False Test "abc" End SubSub Test(Optional ByVal arg As Variant) If IsMissing(arg) Then Debug.Print "a Is Missing" ElseIf arg = True Then Debug.Print "a = True" ElseIf arg = False Then Debug.Print "a = False" Else Debug.Print "a = ?" End If End Sub
Dim strName As String Dim strName1 As String Dim varAddress As Variant Private Sub ListText(x As String, Optional y As Variant) List1.AddItem x If Not IsMissing(y) Then
List1.AddItem y End If End SubPrivate Sub Command1_Click() strName = "第一个参数" Call ListText(strName) '未提供第二个参数 End Sub Private Sub Command2_Click() strName = "第一个参数" strName1 = "第二个参数" Call ListText(strName, strName1) '未提供第二个参数 End Sub
dim a as variant ' 下边的这些IsXXX函数都要求变量是Variant类型的. debug.print IsEmpty(a) ' 这里的a还没有赋初值,所以是IsEmpty(a)为真a = Null debug.print IsNull(a) ' 这里的a的值为Null,所以IsNull(a)返回真call testsub test(optional byval arg as variant) debug.print IsMissing(arg) ' 调用test的时候,没有传递参数(参数arg丢失了),所以IsMissing(arg)返回真 end sub
dim a as variant ' 下边的这些IsXXX函数都要求变量是Variant类型的. debug.print IsEmpty(a) ' 这里的a还没有赋初值,所以是IsEmpty(a)为真a = Null debug.print IsNull(a) ' 这里的a的值为Null,所以IsNull(a)返回真call testsub test(optional byval arg as variant) debug.print IsMissing(arg) ' 调用test的时候,没有传递参数(参数arg丢失了),所以IsMissing(arg)返回真 end sub
Option ExplicitSub Main()
Test
Test True
Test False
Test "abc"
End SubSub Test(Optional ByVal arg As Variant)
If IsMissing(arg) Then
Debug.Print "a Is Missing"
ElseIf arg = True Then
Debug.Print "a = True"
ElseIf arg = False Then
Debug.Print "a = False"
Else
Debug.Print "a = ?"
End If
End Sub
Dim strName1 As String
Dim varAddress As Variant
Private Sub ListText(x As String, Optional y As Variant)
List1.AddItem x
If Not IsMissing(y) Then
List1.AddItem y
End If
End SubPrivate Sub Command1_Click()
strName = "第一个参数"
Call ListText(strName) '未提供第二个参数
End Sub
Private Sub Command2_Click()
strName = "第一个参数"
strName1 = "第二个参数"
Call ListText(strName, strName1) '未提供第二个参数
End Sub
我在字符串型可选参数判断中,常常用 IsNull() 函数。
debug.print IsEmpty(a) ' 这里的a还没有赋初值,所以是IsEmpty(a)为真a = Null
debug.print IsNull(a) ' 这里的a的值为Null,所以IsNull(a)返回真call testsub test(optional byval arg as variant)
debug.print IsMissing(arg) ' 调用test的时候,没有传递参数(参数arg丢失了),所以IsMissing(arg)返回真
end sub
debug.print IsEmpty(a) ' 这里的a还没有赋初值,所以是IsEmpty(a)为真a = Null
debug.print IsNull(a) ' 这里的a的值为Null,所以IsNull(a)返回真call testsub test(optional byval arg as variant)
debug.print IsMissing(arg) ' 调用test的时候,没有传递参数(参数arg丢失了),所以IsMissing(arg)返回真
end sub