将三个向量的值传递给另一个子

时间:2016-12-05 14:32:59

标签: vba excel-vba excel

我有一个子如下:

 Sub simulations(k As Long)
 Dim moAkt() As Double, moShort() As Double, moImmo() As Double
    .
    .
    .
    For l = 1 To length
    .
    .
              ' write into the vectors
                moAkt(l) = zaktie
                moImmo(l) = zImmo
                moShort(l) = zshort
    Next l
    End Sub

我在另一个子calculateColl

中调用此子
  Sub calculateColl
Call simulations
               Dim l As Long
                 Open "C\testfile.txt" For Append As #1
                   For l = 1 To 10
                     Print #1, moImmo(l) ";" zshort(l) ";" moAkt(l)
                     Print #1,
                   Next l
                    Close #1
    End Sub

所以我得到一个错误,因为这个向量在这个子中是未知的。现在我想避免 ByRef,因为我的sub中有另一个变量。如何将所有这三个向量的值传递给新的子calculateColl,以便我可以将它们写入文件中?

1 个答案:

答案 0 :(得分:1)

如果您想从中返回值,那么Sub simulations应该是一个函数。关于返回什么(Collection,2D数组等)有很多选项。我个人声明一个简单的用户类型来保存相关的值:

'Give this a more appropriate name.
Public Type Vector
    Akt As Double
    Immo As Double
    Short As Double
End Type

然后让simulations返回一个数组:

Function simulations(k As Long) As Vector()
    Dim vectors() As Vector
    '...
    For l = 1 To Length
        ' write into the vectors
        vectors(l).Akt = zaktie
        vectors(l).Immo = zImmo
        vectors(l).Short = zshort
    Next l
    simulations = vectors
End Function

最后,在Sub calculateColl

中使用函数的返回值
Sub calculateColl()
    Dim toWrite() As Vector
    toWrite = simulations(whateverKShouldBe)
    Dim l As Long
    Dim handle As Long
    handle = FreeFile
    Open "C\testfile.txt" For Append As #handle
    For l = LBound(toWrite) To UBound(toWrite)
        Print #handle, toWrite(l).Akt; ";"; toWrite(l).Immo; ";"; toWrite(l).Short
        Print #handle,
    Next l
    Close #handle
End Sub

请注意,您应始终使用FreeFile而不是硬编码文件编号。