创建一维动态数组

时间:2016-12-15 01:55:44

标签: arrays vba access-vba ms-access-2013 access

当我不知道数组的大小时,如何向数组添加字段名称?在我下面的两个函数中,我能够填充表没问题,但是当我尝试创建数组时,它只会打印表中的第一条记录。为了使用所有值创建数组,我该怎么做?

Function PopulateTable()
Set rs1 = db.OpenRecordset("MasterList")
For Each fld In rs1.Fields
  StrSQL = "INSERT INTO HoldTable (FieldList) VALUES ('" & fld.Name & "' );"
  DoCmd.SetWarnings False
  DoCmd.RunSQL StrSQL
Next
'Create array of all fld.Name Values
PopulateArray
End Function

Function PopulateArray()
Dim rstData    As DAO.Recordset
Dim v          As Variant
Dim cn         As Variant

Set rstData = CurrentDb.OpenRecordset("select fieldlist from HoldTable")
v = rstData.GetRows(rstData.RecordCount)
For Each cn In v
  Debug.Print CStr(cn)
Next

End Function

3 个答案:

答案 0 :(得分:1)

您应该使用ADODB.Connection和OpenSchema方法获取字段名称列表:List database objects (tables, columns..) using ADO/ADOX

您需要使用rstData.MoveLast然后rstData.MoveFirst来获得准确的RecordCount

Function PopulateTable()
    Set rs1 = CurrentDb.OpenRecordset("MasterList")
    For Each fld In rs1.Fields
        StrSQL = "INSERT INTO HoldTable (FieldList) VALUES ('" & fld.Name & "' );"
        'Create array of all fld.Name Values
        DoCmd.SetWarnings False
        DoCmd.RunSQL StrSQL
    Next
    PopulateArray
End Function

Function PopulateArray()
    Dim rstData As DAO.Recordset
    Dim v As Variant
    Dim cn As Variant

    Set rstData = CurrentDb.OpenRecordset("Select fieldlist FROM HoldTable")
    rstData.MoveLast
    rstData.MoveFirst
    v = rstData.GetRows(rstData.RecordCount)
    For Each cn In v
        Debug.Print CStr(cn)
    Next

End Function

答案 1 :(得分:1)

这是我创建动态数组的方法。 我会遍历数据并在每次迭代中递增数组的大小,然后将值设置为新增加的数组

Dim arraySize as Integer
Dim dynArray() As string
arraySize = -1 ' set to -1 so when you first increment the size by one it will start at index 0

' Iterating through rstData variable
for each fld in rstData.fields
   arraySize = arraySize + 1
   redim preserve dynArray(arraySize) as String
   dynArray(sz) = fld ' not sure if can set it to fld directly or if need to access the value property of fld
next
' End of iterating through

答案 2 :(得分:0)

您可以定义“普通”变量并为其指定一个空数组:

Dim v : v = Array()

然后你可以重新开始它:

ReDim Preserve v(rstData.RecordCount)