【问题标题】:How to save array from one sub to pass it into another?如何从一个子中保存数组以将其传递给另一个?
【发布时间】:2018-06-16 21:00:14
【问题描述】:

例子:

Sub1 生成一个数组 Sub2 使用该数组

唯一有效的方法是在 Sub1() 中调用 Sub2(array as 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 生成的数组并在其他 subs 中使用它而不再次调用它。谢谢

【问题讨论】:

    标签: excel vba


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      为了能够独立调用第二个Sub,请不要使用参数。所以修改这两行代码:

      1. aaa:

        bbb ' Call without argument
        
      2. bbb的定义

        Sub bbb() ' No arguments
        

      【讨论】:

      • 过程调用中多余的括号是potentially dangerous,考虑到 VBA 是如何解释它们的。不要在 VBA 过程/成员调用中加上括号,除非你调用一个带参数的函数或属性获取器。或者,使用已弃用的 Call 关键字。
      • @Mat'sMug,括号已删除。谢谢。
      猜你喜欢
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      相关资源
      最近更新 更多