将数组传递给子例程 VBA

Passing an array to subroutine VBA

我正在为 excel 开发一个宏,并且有一个将数组传递给另一个子程序的子程序,但我不断收到

Run time error '9'

Subscript out of range

下面是我的代码,我留下了一条评论指出发生此错误的位置。我是 VBA 的新手,所以我可能会尝试错误地传递一个数组,但不确定。

'Main Driver
Sub Main()
    WorkbookSize = size() 'Run function to get workbook size
    newbook = False
    Call create            'Run sub to create new workbook
    Call pull(WorkbookSize)              'Run sub to pull data
End Sub

'Get size of Worksheet
Function size() As Integer
    size = Cells(Rows.Count, "A").End(xlUp).Row
End Function

'Create workbook
Sub create()
    Dim wb As Workbook
    Set wb = Workbooks.Add
    TempPath = Environ("temp")
    With wb
        .SaveAs Filename:=TempPath & "EDX.xlsm" _
        , FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

        .ChangeFileAccess Mode:=xlReadOnly, WritePassword:="admin"
    End With
End Sub

'pull data
Sub pull(size)
    Dim code() As Variant
    For i = 1 To size
    'Check code column fo IN and Doctype column for 810
        If Cells(i, 18).Value = "IN" Then
            code(i) = Cells(i, 18).Value 'store in array
        End If
    Next i
     Call push(code)
End Sub

'push data to new workbook
Sub push(ByRef code() As Variant)
    activeBook = "TempEDX.xlsm"
    Workbooks(activeBook).Activate 'set new workbook as active book
    For i = 1 To UBound(code)   ' <---here is where the error is referencing
        Cells(i, 1).Value = code(i)
    Next i
End Sub

感谢任何帮助。

你的问题是你没有正确初始化代码数组。

这样做使用 Redim 请参阅下面的修改:

    'pull data
    Sub pull(size)
        Dim code() As Variant
        Redim code(size-1)  '<----add this here minus 1 because 0 index array
        For i = 1 To size
        'Check code column fo IN and Doctype column for 810
            If Cells(i, 18).Value = "IN" Then
                code(i-1) = Cells(i, 18).Value 'store in array subtract 1 for 0 index array
            End If
        Next i
         Call push(code)
    End Sub

此外,您需要更新 Push 方法的代码以适应 0 索引数组

'push data to new workbook
Sub push(ByRef code() As Variant)
    activeBook = "TempEDX.xlsm"
    Workbooks(activeBook).Activate 'set new workbook as active book
    For i = 0 To UBound(code)   ' <0 to ubound
        Cells(i+1, 1).Value = code(i) 'add 1 to i for the cells reference
    Next i
End Sub

我会补充这些其他要点

您也在使用 Rows,但将 Integer 作为 return 用于有溢出风险的函数 例如

Function size() As Integer

更改为 Long

您有很多隐式活动sheet 引用。摆脱那些并给出 parent sheet。例如,您可以在名为 ws 的变量中设置 sheet 并在需要时将其作为参数传递。

例如

Public Function size(ByVal ws As Worksheet) As Long
    With ws
        size = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With
End Function

如前所述,将 Option Explicit 放在代码的顶部并声明所有变量。