VBA功能可选参数 [英] VBA Function Optional parameters
本文介绍了VBA功能可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我多次调用特定的代码,因此我想使用可选参数. 我可以这样写:
I am calling a specific piece of code several times therefore I would like to use optional parameters. I can write something like:
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
如何更改功能以容纳1个以上的可选参数?
How can I change the function to hold more than 1 optional parameters?
类似的东西:
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的建议,我设法将其更改为:
Following Pankaj Jaju's advice, I have managed to have it run by changing it to:
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
现在,如何清除可选参数的值?在进行某些计算时,我将需要它.像这样:
Now, how can I clear the value of an optional parameter? I will need this for some of the calculations. Something like:
Set strA = Nothing
推荐答案
更改子项并添加ByVal
Public Sub CalculateMe(Optional ByVal strA As String, Optional ByVal strB As String)
这篇关于VBA功能可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文