VBA函数或子WITHOUT声明了许多数组

时间:2016-05-29 06:03:51

标签: vba

我必须使用不同的输入参数重播一些代码,并且我想创建item = rowData[columns[c]];sub以使更短的代码而不用声明超过30个数组和参数。请看下面的例子。

function

我想将循环移动到新的子或函数。第二个调用looper应该在执行第一个looper之后使用数组b()。

Sub main()

ReDim a(1 To 18) As Integer
ReDim b(1 To 18) As Integer

'first loop
start_1 = 1
stop_1 = 4
For i = start_1 To stop_1
    b(i) = b(i) + a(i)
Next i

'second loop
start_2 = 2
stop_2 = 6
For i = start_1 To stop_1
    b(i) = b(i) + a(i)
Next i

'third loop
start_3 = 3
stop_3 = 9
For i = start_1 To stop_1
    b(i) = b(i) + a(i)
Next i

End Sub

如何在没有声明输入参数的情况下调用looper,比如looper a,b,1,4,但是在sub中使用它们?

1 个答案:

答案 0 :(得分:1)

在OP的进一步需求之后

编辑

这是最直接的方式

Option Explicit

Sub looper(a() As Integer, b() As Integer, iStart As Integer, iStop As Integer)
    Dim i As Integer
    For i = iStart To iStop
        b(i) = b(i) + a(i)
    Next i
End Sub


Sub main()
    ReDim a(1 To 18) As Integer
    ReDim b(1 To 18) As Integer

    'first loop
    looper a, b, 1, 4

    'second loop
    looper a, b, 2, 6

    'third loop
    looper a, b, 3, 9
End Sub

另一种可能性是使用模块级变量,如下所示

Option Explicit

'Module Level variable declarations make them "visible" in every Sub or Function inside the same Module you place them in
Dim a(1 To 18) As Integer
Dim b(1 To 18) As Integer
Dim iStart As Integer, iStop As Integer

Sub looper()
    Dim i As Integer
    For i = iStart To iStop
        b(i) = b(i) + a(i)
    Next i
End Sub


Sub main()
    'first loop
    iStart = 1: iStop = 4
    looper

    'second loop
    iStart = 2: iStop = 6
    looper

    'third loop
    iStart = 3: iStop = 9
    looper
End Sub

你是否需要对数组进行ReDim,如下所示(对于模块级变量方法):

Option Explicit
'these are Module Level variable declarations so they are "seen" in every Sub/Function inside the same Module you place them in
Dim a() As Integer '<~~ declare array as of variable dimensions
Dim b() As Integer '<~~ declare array as of variable dimensions
Dim iStart As Integer, iStop As Integer

Sub looper()
    Dim i As Integer
    For i = iStart To iStop
        b(i) = b(i) + a(i)
    Next i
End Sub


Sub main()
    ReDim a(1 To 18) As Integer '<~~ redim array
    ReDim b(1 To 18) As Integer '<~~ redim array
    'first loop
    iStart = 1: iStop = 4
    looper

    'second loop
    iStart = 2: iStop = 6
    looper

    'third loop
    iStart = 3: iStop = 9
    looper
End Sub