在单个函数中作为函数传递多个值



在Python中,当我们必须多次调用参数时,我们通常会在函数中传递参数,如下所示:

def function_add(a,b):
print(a+b)
function_add(4,5)
function_add(5,7)
function_add(10,4)
function_add(4,6)

我们也有类似的方法在VBA中实现它吗?我试着实现它,但没能实现。下面是我的代码。

Private Sub SearchAndInsertRows()
Dim rng As Range
Dim cell As Range
Dim search As String
Dim kk As String
Set rng = ActiveSheet.Columns("A:A")
search = ""
Call searchGetKey(search)
Set cell = rng.Find(What:=search, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)
If cell Is Nothing Then
MsgBox "Not Found"
Else
kk = ""
Call searchSetKey(kk)
cell.Value = kk   
End If
End Sub
Sub searchGetKey(ByRef getKey As String)
getKey = "a"
End Sub  
Sub searchSetKey(ByRef setKey As String)
setKey = "b"       
End Sub

子searchGetKey和searchSetKey修改一个单元格,但我需要对单元格的数量做同样的操作。还有其他方法吗?

请随时优化代码。

非常感谢

VBA中的函数必须返回一些东西。否则,您应该使用Sub:
Function function_add(a As Long, b As Long) As Long
function_add = a + b
End Function
Sub TestFunction()
MsgBox function_add(3, 5)
End Sub

您可以使用不带参数的函数,只需根据特定的计算算法返回即可。例如:

Function tomorrow_Date() As Date
tomorrow_Date = Date + 1
End Function

可以称为:

Sub testTommorrow_Date()
MsgBox tomorrow_Date
End Sub

或者默认采用参数ByRefSub,如果未指定ByVal:

Sub Sub_add(a As Long, b As Long, c As Long)
c = a + b
End Sub

并测试为:

Sub TestSub_Add()
Dim c As Long
Sub_add 3, 2, c
MsgBox c
End Sub

当然,ab可以在测试Sub中声明,并像参数一样使用,但我想说的是,它们与调用后更新的c无关。。。

最新更新