Pro*_*oVB 16 vba function optional-parameters
我多次调用一段特定代码,因此我想使用可选参数.我可以这样写:
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
Pan*_*aju 12
更改您的子并添加 ByVal
Public Sub CalculateMe(Optional ByVal strA As String, Optional ByVal strB As String)
Public Sub CalculateMe(Optional varA As Variant, Optional varB as Variant)
摘自Chip Pearson的优秀解释:
管理可选参数使用的规则:
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.
| 归档时间: | 
 | 
| 查看次数: | 65174 次 | 
| 最近记录: |