将数组传递给子例程VBA

时间:2018-08-31 14:23:34

标签: arrays vba excel-vba subroutine

我正在为Excel编写宏,并且有一个将数组传递给另一个子的子,但是我一直在获取

  

运行时错误“ 9”

     

下标超出范围

下面是我的代码,我在注释中指出了发生此错误的位置。我是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

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

我将添加其他要点

您也正在使用Rows,但使用Integer作为函数可能会有溢出的返回 例如

Function size() As Integer

更改为Long

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

例如

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放在代码的顶部,并声明所有变量。

答案 1 :(得分:1)

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

使用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