声明数组输入参数

时间:2015-09-08 15:03:17

标签: arrays excel vba

我只是使用已知长度的数组作为VBA子/函数的输入参数而遇到很多麻烦。我在其他答案中尝试了一些修复/解决方法,但由于某种原因,它们都没有工作。

我仍然无法让它工作,这是我实际代码的一个例子:

Sub toDo()

ReDim thisArray(1 To 4, 1 To 10): k = 1
For i = 1 To 4
For j = 1 To 10
thisArray(i, j) = k
k = k + 1
Next: Next

pasteArray(Ubound(thisArray,1), Ubound(thisArray,2),2,2,thisArray)

End Sub

Public Sub pasteArray(x As Integer, y As Integer, _
locX As Integer, locY As Integer, _
ParamArray myArray() As Variant)

ReDim myArray(1 To x, 1 To y) As Double
Range(Cells(locX, locY), Cells(x + locX - 1, y + locY - 1)) = myArray

End Sub

我只想将thisArray()传递给单元格(2,2),但我现在得到一个编译错误:语法错误,在我的toDo Sub中调用pasteArray sub的行。

我也在同一行上得到一个编译错误:Expecting =。我不知道为什么它不应该返回任何东西。

2 个答案:

答案 0 :(得分:0)

试试这样:

Sub mainToDo()
    Dim someArray(1 To 10) As Integer
    Dim i As Integer: i = 1
'    For Each ind In someArray
'        ind = i
'        i = i + 1
'    Next
    For j = 1 To 10
        someArray(j) = i
        i = i + 1
    Next

    useArray (someArray)

End Sub

Sub useArray(arr As Variant)
    For i = LBound(someArray) To UBound(arr)
        Debug.Print arr(i)
    Next
End Sub  

我已评论过您的For...Loop,因为它没有存储该值。

答案 1 :(得分:0)

Sub mainToDo()
Dim someArray(1 To 10) As Integer
Dim ind
  ' Dim someArray(1 To 10)
    Dim i As Integer: i = 1
    For Each ind In someArray
        ind = i
        i = i + 1
    Next
    useArray someArray
End Sub

然后设置第二个子。像这样:

Sub useArray(ByRef someArray() As Integer)
Dim i As Integer

For i = LBound(someArray) To UBound(someArray)
    Debug.Print someArray(i)
    ' Do whatever you want here, with each array item.
Next i
End Sub

注意:您当前的mainToDo()未在someArray中设置任何值,因此第二个子网只会为数组中的每个项目打印0

此外,您可以将数组作为全局变量传递,并将其用作此类(例如,请参阅this thread)。