尝试使用带variables的范围函数填充数组时出错

我有一个问题填充数组。 出于某种原因,我能find的所有教程都会在代码中明确列出数据的大小(这种types的使用VBA的目的是为了开始这个任务)。

我的问题是关于如何dynamic调整数组的大小,如果甚至有可能以我想要的方式进行调整。 代码本身是与背景和具体问题进行评论。

当我运行代码时,我得到一个“应用程序定义或对象定义的错误”(1004)

此外,使用for … next循环来填充数组可能最终在计算上效率低下,因为数据集通常平均为23k行

码:

Sub DCList() ReDim DCList(0, 0) Dim cnum As Integer ' count the number of columns that have been used in the workbook cnum = ActiveWorkbook.Sheets("data").UsedRange.Columns.Count ' set array dimensions to 1 row & Cnum columns ReDim DCList(1, cnum) ' set array values to values found in the range (A1, cnum 1) DCList = ActiveWorkbook.Sheets("data").Range(Cells(1, 1), Cells(1, cnum)).Value 'Other info: ' DCList is a global variable set as Variant type ' The overarching goal of this sub is purely to determine the column names of ' a dataset so that (in another sub) the user can select which column to lookup End Sub 

试试这个版本:

 Sub DCList_sub() Dim DCList Dim cnum As Long ' count the number of columns that have been used in the workbook cnum = ActiveWorkbook.Sheets("data").UsedRange.Columns.Count ' set array dimensions to 1 row & Cnum columns ReDim DCList(1 To 1, 1 To cnum) ' set array values to values found in the range (A1, cnum 1) DCList = ActiveWorkbook.Sheets("data").Range(Cells(1, 1), Cells(1, cnum)).Value 'Other info: ' DCList is a global variable set as Variant type ' The overarching goal of this sub is purely to determine the column names of ' a dataset so that (in another sub) the user can select which column to lookup End Sub 

如果您希望DCList包含工作表的第一行,则不需要重新设置DClist。 只是:

 Dim DCList As Variant DCList = ActiveWorkbook.Sheets("Data").UsedRange.Rows(1) 

应该这样做。

如果因为其他原因需要列数

 cnum = ubound(DCList,2) 

加里的学生代码纠正:

 Sub DCList_sub() Dim DCList() as variant Dim cnum As Long with ActiveWorkbook.Sheets("data") 'might be better with thisworkbook, if the code is in the same workbook... ' count the number of columns that have been used in the workbook cnum = .UsedRange.Columns.Count ' set array dimensions to 1 row & Cnum columns ReDim DCList(1 To 1, 1 To cnum) ' set array values to values found in the range (A1, cnum 1) DCList = .Range(.Cells(1, 1), .Cells(1, cnum)).Value 'note the two "." before "Cells" end with 'do stuff here with the array... 

'可用内存擦除DClist

结束小组