我在填充数组时遇到问题。出于某种原因,我能找到的所有教程都宁愿列出数据和数据。在代码本身中明确地调整大小(这种方式违背了使用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
答案 0 :(得分:1)
试试这个版本:
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
答案 1 :(得分:0)
如果您希望DCList包含工作表的第一行,则无需重新设置DClist。简单地:
Dim DCList As Variant
DCList = ActiveWorkbook.Sheets("Data").UsedRange.Rows(1)
应该这样做。
如果由于其他原因需要列数
cnum = ubound(DCList,2)
答案 2 :(得分:0)
加里的学生代码更正:
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
End Sub