【发布时间】:2016-09-04 17:00:01
【问题描述】:
我对动态数组有一些奇怪的行为。似乎 VBA 拒绝为变量赋值。代码如下:
Private Sub Report_Load()
Dim db As Database
Dim reportArray() As Variant
Dim structre As Recordset
Dim columns, rows, i As Integer
'Open recordset
Set db = CurrentDb
Set structure = db.OpenRecordset("SELECT * FROM [tblstructure] ORDER BY [Rank]")
'Change array size dynamically
rows = structure.RecordCount
columns = 4
ReDim reportArray(rows, columns)
'Populate array
i = 0
Do Until structure.EOF
reportArray(i, 0) = structure![Name]
i = i + 1
structure.MoveNext
Loop
End Sub
当我打开报告时,我收到下标超出范围的错误。当我调试我的代码时,我可以看到循环中 i 的值为 2,所以我的数组必须小于那个值。当我将鼠标悬停在 rows 变量上时,我看到它的值为 1。所以确实我正在尝试访问超出范围的内容。但奇怪的是structure.RecordCount的值是23。
截图:
即使我使用这样的代码:
ReDim reportArray(structure.RecordCount, columns)
我得到一个大小为 (1, 4) 的数组。为什么 VBA 不将值 23 分配给变量“行”,或者为什么 ReDim 将正确的值分配给第二维,而不是第一维?
【问题讨论】:
-
你应该学习DAO.Recordset的
GetRows()方法。