Reputation: 13
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
Upvotes: 0
Views: 2153
Reputation: 349946
To make it possible to call the second Sub
independently, don't use an argument. So change these two lines of code:
In aaa
:
bbb ' Call without argument
The definition of bbb
Sub bbb() ' No arguments
Upvotes: 1
Reputation: 7465
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
Upvotes: 1