【发布时间】:2014-07-27 16:36:05
【问题描述】:
我在填充数组时遇到问题。出于某种原因,我能找到的所有教程都宁愿在代码本身中明确列出数据和调整大小(这有点违背了使用 VBA 开始这项任务的目的)。
我的问题是关于如何动态调整数组大小,如果它甚至可以按照我尝试的方式这样做的话。代码本身带有背景和具体问题的注释。
当我运行代码时,我收到“应用程序定义或对象定义错误”(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
【问题讨论】:
-
感谢 Gary 的学生,当你这样做时,他正试图弄清楚如何正确格式化这个东西。
-
将 ActiveWorkbook.Sheets("data").Range(Cells(1, 1), Cells(1, cnum)).Value 替换为 ActiveWorkbook.Sheets("data").Range(ActiveWorkbook. Sheets("data").Cells(1, 1), ActiveWorkbook.Sheets("data").Cells(1, cnum)).Value ?