简体   繁体   English

丢失对已分配数组的引用 - 下标超出范围

[英]Losing Reference to an Assigned array - Subscript out of Range

I have an Array declared in my Main Class (VBA Module).我在主类(VBA 模块)中声明了一个数组。 however, i'm trying to call a function that essentially reads an Excel sheet, looks for a specific table definition on a specific sheet and returns an array populated with the contents of the Excel Table.但是,我正在尝试调用一个函数,该函数本质上是读取 Excel 工作表,在特定工作表上查找特定表定义并返回一个填充有 Excel 表内容的数组。

My Function does not seem to want to update the defined array.我的函数似乎不想更新定义的数组。 please help.请帮忙。 would passing the defined array as a function input work better?将定义的数组作为函数输入传递会更好吗?

code below:代码如下:

' -----   main Module  ----

'declare my Array
Dim MyArr() As Variant

Call ReadXLFileIntoArray(excelFileAddress, excelFileSheet)

Debug.Print (MyArr(1, 1))  ' raises Subscript out of range error

'- Excel Data Processing Module

Function ReadXLFileIntoArray(addr As String, sheet As Integer)
    Dim xls     As Excel.Application
    Dim wkb     As Excel.Workbook
    Dim wks     As Excel.worksheet

    Set xls = New Excel.Application
    Set wkb = xls.Workbooks.Open(addr, ReadOnly:=True)
    Set wks = wkb.Worksheets(sheet)

    Call pushToArray(xls, wks, "excelTableName", MyArr)

    wkb.Close True
    Set wks = Nothing
    Set wkb = Nothing
    xls.Quit
    Set xls = Nothing
End Function

Function pushToArray(ByRef XL As Object, ByRef wks As worksheet, tableName As String, ByRef Arr As Variant)
Dim tmpArr As Variant
Dim x As Integer, y As Integer
r = wks.ListObjects(tableName).DataBodyRange.Rows.Count - 1
c = wks.ListObjects(tableName).DataBodyRange.Columns.Count - 1

    'ReDim Arr(c, r)  ' do i need to call this?
    tmpArr = wks.ListObjects(tableName).DataBodyRange.Value
    Set Arr = XL.Transpose(tmpArr)
    Debug.Print ("Loaded from Excel: " & " Records: " & wks.ListObjects(tableName).DataBodyRange.Rows.Count & "" & tableName)

    Debug.Print (Arr(1, 1))  ' works!

End Function

I would arrange it more like this:我会更像这样安排它:

' -----   main Module  ----
Sub Tester()
    Dim MyArr As Variant, excelFileAddress As String, excelFileSheet As Long
    '...
    '...
    MyArr = ReadXLListIntoArray(excelFileAddress, excelFileSheet, "excelTableName")
    Debug.Print MyArr(1, 1)
End Sub


'- Excel Data Processing Module
Function ReadXLListIntoArray(addr As String, sheet As Long, listName As String)
    Dim xls     As Excel.Application
    Dim wkb     As Excel.Workbook
    
    Set xls = New Excel.Application
    Set wkb = xls.Workbooks.Open(addr, ReadOnly:=True)
    
    ReadXLListIntoArray = wkb.Worksheets(sheet).ListObjects(listName).DataBodyRange.Value

    wkb.Close False
    xls.Quit
End Function

Not sure if you need that Transpose or not...不确定您是否需要Transpose ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM