我多次调用一段特定代码,因此我想使用可选参数。 我可以这样写:
Public Sub main()
strA = "A"
'Calling the function
CalculateMe (strA)
End Sub
Public Sub CalculateMe(strA As String)
Set rs = DB.OpenRecordset("tbl_A")
rs.MoveFirst
Do Until rs.EOF
If rs.Fields(0) = strA Then
dblA = rs.fields(2).Value
End If
rs.MoveNext
Loop
End Sub
如何更改函数以保存多个可选参数?
类似的东西:
Public Sub main()
strA = "A"
strB = "B"
'Calling the function
CalculateMe (strA, strB)
more code
End Sub
Public Sub CalculateMe(Optional strA As String, Optional strB as String)
Set rs = DB.OpenRecordset("tbl_A")
rs.MoveFirst
Do Until rs.EOF
If rs.Fields(0).Value = strA And rs.Fields(1).Value = strB Then
dblA = rs.Fields(2).Value
End If
rs.MoveNext
Loop
End Sub
根据Pankaj Jaju的建议,我已经成功将其改为:
Public Sub main()
strA = "A"
strB = "B"
'Calling the function
dblA = CalculateMe (strA, strB)
End Sub
Public Function CalculateMe(Optional ByVal strA As String, Optional ByVal strB as String)
Set rs = DB.OpenRecordset("tbl_A")
rs.MoveFirst
Do Until rs.EOF
If rs.Fields(0).Value = strA And rs.Fields(1).Value = strB Then
dblA = rs.Fields(2).Value
End If
rs.MoveNext
Loop
End Sub
现在,我如何清除可选参数的值?我需要这个来进行一些计算。类似的东西:
Set strA = Nothing
答案 0 :(得分:12)
更改您的子广告并添加ByVal
Public Sub CalculateMe(Optional ByVal strA As String, Optional ByVal strB As String)
答案 1 :(得分:6)
Public Sub CalculateMe(Optional varA As Variant, Optional varB as Variant)
摘自Chip Pearson's出色的解释:
管理可选参数使用的规则:
Optional
关键字才能使参数可选。Variant
数据
类型。 IsMissing
函数仅适用于声明的参数
为Variant
。与其他任何数据类型一起使用时,它将返回False
。Function Test(L1 As Long, L2 As Long, _
Optional P1 As Variant, Optional P2 As Variant) As String
Dim S As String
If IsMissing(P1) = True Then
S = "P1 Is Missing."
Else
S = "P1 Is Present (P1 = " & CStr(P1) & ")"
End If
If IsMissing(P2) = True Then
S = S & " " & "P2 Is Missing"
Else
S = S & " " & "P2 Is Present (P2 = " & CStr(P2) & ")"
End If
Test = S
End Function
这里,L1和L2都是必需的,但P1和P2是可选的。由于两者都是Variant
类型,我们可以使用IsMissing
来确定参数是否已传入。IsMissing
如果省略True
参数则返回Variant
,或者如果包含False
参数,则Variant
。如果可选参数的数据类型是Variant
以外的任何数据类型,IsMissing
将返回False
。
答案 2 :(得分:1)
我不确定你的意思是"可选"。在您的示例中,您将args列为可选项,但您仍然将两个参数传递给该函数。
无论如何,在这里你传递两个参数:
Public Sub main()
strA = "A"
strB = "B"
'Calling the function
dblA = CalculateMe(strA, strB)
more code
End Sub
如果您只想传递其中一个参数,请执行以下操作:
dblA = CalculateMe(, strB)
或者:
dblA = CalculateMe(strA)
否则,如果你总是传递两个参数,那么让它们Optional
是没有意义的。