存储到函数VBA的可变结果中

时间:2015-05-26 12:39:55

标签: excel vba excel-vba

我有一个进行特定计算的功能。然后,我有一个子程序,我想从中调用该函数并用它来制作一些东西。我相信我应该在函数末尾返回一个值(" counter")然后将它存储在sub上,但是我该怎么做?

var completed =[];
 var visited = [] ;
 var id = 0

function breadth (id) {
    completed.push(id);
    if (graph[id][1].length > 0){
      for (i in graph[id][1]){
          node = graph[id][1][i];
          id = node.id ;
          visited.push (i) ;
          breadth(id);  
      }

    }
}
breadth (id) ;

3 个答案:

答案 0 :(得分:2)

在VBA中,您不会使用return语句返回结果。您将值分配给函数名称。该功能不必使用" As Integer"键入。默认情况下,它将作为变量返回。因此,以这种方式修改样本将使其有效。

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

答案 1 :(得分:0)

您可以将函数指定为具有数据类型Integer,并将count的值分配给函数末尾。

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)的代码

答案 2 :(得分:0)

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