示例:
Sub1生成一个数组 Sub2使用该数组
唯一可行的方法是在Sub1()中调用Sub2(数组作为Variant)。我全局声明数组变量。
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
如果我不在sub aaa中调用sub bbb,它甚至不让我执行sub bbb。它的唯一工作方式是上面的代码,但我不想每次调用sub bbb时调用sub aaa,我想保存sub aaa生成的数组,并在其他sub中使用它而不再调用它。谢谢
答案 0 :(得分:1)
我想建议让aaa返回数组而不是使用公共变量。
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
答案 1 :(得分:1)
为了能够独立调用第二个Sub
,请不要使用参数。所以改变这两行代码:
在aaa
:
bbb ' Call without argument
bbb
Sub bbb() ' No arguments