简体   繁体   中英

How to save array from one sub to pass it into another?

Example:

Sub1 generates an array Sub2 Uses that array

The only time it works is by calling Sub2(array as Variant) inside Sub1(). I declare the array variable globally.

Dim arr1() As Variant
Sub aaa()


Dim col As Integer
Dim row As Integer

startingPoint = "B2"


col = Range(startingPoint).Column
row = Range(startingPoint).row

cols = Range(Cells(row, col), Cells(row, col).End(xlToRight)).Count
ReDim arr1(cols)

For myCounter = 1 To cols
    arr1(myCounter) = Cells(row, col + myCounter - 1).Value
Next

For myCounter = 1 To cols
    Cells(myCounter, 1).Value = arr1(myCounter)
Next

bbb (arr1)


End Sub

Sub bbb(arr1 As Variant)
Dim myCounter As Integer
For myCounter = 1 To 4
    Cells(myCounter, 1).Value = arr1(myCounter)
Next
End Sub

If i dont call sub bbb inside sub aaa, it doesnt even let me to execute sub bbb. The only way it works is the code above, but i dont want to call sub aaa everytime i need to call sub bbb, i want to save the array generated by sub aaa and use it in other subs without calling it again. Thank you

I'd like to recommend to have aaa return the array instead of using a public variable.

Function aaa()




Dim col As Integer
Dim row As Integer

startingPoint = "B2"


col = Range(startingPoint).Column
row = Range(startingPoint).row

cols = Range(Cells(row, col), Cells(row, col).End(xlToRight)).Count
Dim arr1(cols) as Variant

For myCounter = 1 To cols
    arr1(myCounter) = Cells(row, col + myCounter - 1).Value
Next

For myCounter = 1 To cols
    Cells(myCounter, 1).Value = arr1(myCounter)
Next

aaa = arr1

End Function

Sub bbb()
   Dim arr1() as Variant 
   arr1 = aaa()

Dim myCounter As Integer
For myCounter = 1 To 4
    Cells(myCounter, 1).Value = arr1(myCounter)
Next
End Sub

To make it possible to call the second Sub independently, don't use an argument. So change these two lines of code:

  1. In aaa :

     bbb ' Call without argument 
  2. The definition of bbb

     Sub bbb() ' No arguments 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM