VBA 数组动态调整大小

问题描述 投票:0回答:1

我有一个函数,我试图通过保存选择中的列名并使用该输出将插入写入来创建插入语句。因此,我尝试创建一个二维数组,用区域(651,652 和 801)填充第一个槽,用列名填充第二个槽,我可以从选择中获取列名。

所以我的函数是这样开始的:

Function create_insert() as boolean

Dim arrCol(0 to 2, 0 to 75) as variant

Dim A(0 to 2) as variant

A(0) = "651"
A(1) = "652"
A(2) = "801"

Set dbs=currentdb()

For i = lbound(A) to 2

Set rs= dbs.openrecordset("select...". & A(i))

Do while not rs.eof

  ArrCol(i,0) = A(i)
  ArrCol(i,i+j)=rs(0).Value
  J=j +1
  rs.movenext
Loop

Next i

但是我在数组的尺寸方面遇到了问题。因为我希望它更加动态,而不是 75,所以我将其静态定义为。

顺便说一句,我从中获取列的是 3 个表(areas-651,652,801),所以我需要信息、表和列。

arrays vba ms-access
1个回答
0
投票

除非 Function 返回值或需要通过宏或查询调用,否则可以只是 Sub。

声明没有维度的数组,然后根据记录集 Recordcount 进行 Redim。

Sub create_insert()

Dim arrCol() As Variant
Dim A(0 To 2) As Variant
Dim dbs As DAO.Database, rs As DAO.Recordset, i As Integer, j As Integer

A(0) = "651"
A(1) = "652"
A(2) = "801"

Set dbs = CurrentDb()

For i = 0 To 2
    Set rs = dbs.OpenRecordset("SELECT * FROM table WHERE field='" & A(i) & "'")
    rs.MoveLast
    rs.MoveFirst
    ReDim arrCol(3, rs.RecordCount)
    j = 1
    Do While Not rs.EOF
      arrCol(i, 0) = A(i)
      arrCol(i, j) = rs(0).Value
      Debug.Print arrCol(i, 0), arrCol(i, j)
      j = j + 1
      rs.MoveNext
    Loop
Next i
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.