存储到函数VBA的variables结果中

我有一个function,使一个特定的计算。 然后,我有一个子程序,我想调用这个函数,并用它做一些东西。 我相信我应该返回一个值(“计数器”)在函数的结尾,然后将其存储在子,但我该怎么做?

Function thisFunction(int1 As Integer, int2 As Integer) Dim counter As Integer counter = 0 Dim i As Integer For i = 1 To 10 counter = int1 + int2 Next End Function Sub getResult() Dim result As Integer result = thisFunction(5, 2) MsgBox (result) End Sub 

在VBA中,您不会返回带有return语句的结果。 您将该值分配给函数名称。 该函数不需要用“As Integer”键入,默认情况下它将作为variables返回。 因此,以这种方式修改您的示例将使其工作。

 Function thisFunction(int1 As Integer, int2 As Integer) Dim counter As Integer counter = 0 Dim i As Integer For i = 1 To 10 counter = int1 + int2 Next thisFunction = counter End Function Sub getResult() Dim result As Integer result = thisFunction(5, 2) MsgBox (result) End Sub 
 Public Function thisFunction(int1 As Integer, int2 As Integer) As Integer Dim counter As Integer counter = 0 Dim i As Integer For i = 1 To 10 counter = counter + int1 + int2 Next i thisFunction = counter End Function Sub getResult() Dim result As Integer result = thisFunction(5, 2) MsgBox (result) End Sub 

您将指定您的函数具有数据typesInteger ,并将计数器的值分配给函数结束。

 Function thisFunction(int1 As Integer, int2 As Integer) As Integer Dim counter As Integer counter = 0 Dim i As Integer For i = 1 To 10 counter = int1 + int2 Next thisFunction = counter End Function 

我还想指出的是,函数循环冗余10次。 你应该这样解决它:

你会这样做:

 For i = 1 To 10 counter = counter + int1 + int2 Next 

所以以前的值被添加到计数(如果这是你正在计划,否则循环是多余的)

编辑修改了VBA(而不是VB.NET)的代码