2016-07-08 45 views
0

我有一個函數,我想創建一個數組,但它不允許我在函數內部ReDim數組。VBA函數中的ReDim無效

Function engArray(rigStck As Variant) As Variant 
    'CREATE ENGINE ARRAY WITH #, USAGE DAYS AND USED? 
    If rigStck <> 0 Then 
     ReDim engArray(1 To rigStck, 2) 
     For n = 1 To UBound(engArray) 
      'engine numbering 
      engArray(n, 0) = n 
      'reset engine usage to 0 
      engArray(n, 1) = 0 
      engArray(n, 2) = 0 
     Next 
    Else 
     engArray(1, 0) = 0 
    End If 
End Function 
+3

使用一個臨時數組'暗淡TmpArray()作爲variant'然後REDIM臨時數組你想要的大小。然後在結尾'engarray = TmpArray' –

+0

完美。乾杯! – peetman

+1

正如Scott提供的解決方案,原因是你的函數本身不是一個數組本身,它可以是redim – MatthewD

回答

0

要重新創建多維數組,您需要具有創造性。你只能固有地修改外部維度,所以你需要做類似的事情。如果你需要在1,而不是0開始,你會想調整它一點:

Public Function ReDimPreserve(aArrayToPreserve, nNewFirstUBound, nNewLastUBound) 'returns array with lbound starting at 0 and ending at designated amount 
    ReDimPreserve = False 
    'check if its in array first 
    If IsArray(aArrayToPreserve) Then 
     'create new array 
     ReDim aPreservedArray(nNewFirstUBound, nNewLastUBound) 
     'get old lBound/uBound 
     nOldFirstUBound = UBound(aArrayToPreserve, 1) 
     nOldLastUBound = UBound(aArrayToPreserve, 2) 
     'loop through first 
     For nFirst = LBound(aArrayToPreserve, 1) To nNewFirstUBound 
      For nLast = LBound(aArrayToPreserve, 2) To nNewLastUBound 
       'if its in range, then append to new array the same way 
       If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then 
        aPreservedArray(nFirst, nLast) = aArrayToPreserve(nFirst, nLast) 
       End If 
      Next 
     Next 
     'return the array redimmed 
     If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray 
    End If 
End Function