[英]Passing an array to subroutine VBA
我正在為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
任何幫助表示贊賞。
我將補充其他幾點
您也正在使用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
放在代碼的頂部,並聲明所有變量。
您的問題是您沒有正確初始化代碼數組。
使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.