gpt4 book ai didi

VBA 函数 可选参数

转载 作者:行者123 更新时间:2023-12-02 07:47:08 28 4
gpt4 key购买 nike

我多次调用特定的代码段,因此我想使用可选参数。我可以写这样的东西:

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 个以上可选参数?

类似于:

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

最佳答案

更改您的子项并添加 ByVal

Public Sub CalculateMe(Optional ByVal strA As String, Optional ByVal strB As String)

关于VBA 函数 可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28770412/

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