将查询表中的字段名称存储到动态数组MS Access中

问题描述

我有一个查询qryRuleSets,它输出带有19个字段的表(建议不要在此之前保存到访问表中)。我想获取字段名称并将其存储到数组中,以便稍后可以在for循环中使用该数组。

要查找查询结果(稍后在for循环中使用)中的字段数,我实现了以下内容,其中字段数存储在变量{{1}中}-

numberfields

要真正获得这些字段的名称并将它们存储在数组中,我遇到了两个问题:

1。从查询结果中获取字段名称

2。设置动态数组,以便如果查询最终返回的表多于或少于少于19个字段,则该表仍将起作用

我的第一个问题:

我尝试按照以下链接中的步骤操作:Get Column name from a query table,但我无法弄清楚。

要从qry结果中获取字段名称,我尝试了以下操作,但是我对vba / access的了解并不多,因此即使经过大量的搜索,也很难理解:

numberfields = CurrentDb.QueryDefs("qryrulesets").Fields.Count

第二个问题:

要将值存储在数组中,我尝试了以下(作为测试),它可以工作,但我必须定义数组的大小。有没有一种方法可以动态化,即基于(上面存储在Dim qry As QueryDef Dim fieldNames As QueryDef Dim firstcol As String Set fieldNames = CurrentDb.createqueryDef(qry.qryrulesets) firstcol = fieldNames.field(0).Name 中的字段数)的值

numberfields

我尝试将上面的“ 30”设置为可变值,但它不是这样。

任何人和所有帮助将不胜感激。谢谢!

解决方法

您可以这样做:

Public Function GetFieldNames(ByVal QueryName As String) As String()

    Dim Query           As DAO.QueryDef
    
    Dim FieldNames()    As String
    Dim Index           As Integer
    
    Set Query = CurrentDb.QueryDefs(QueryName)
    
    ReDim FieldNames(0 To Query.Fields.Count - 1)
    For Index = LBound(FieldNames) To UBound(FieldNames)
        FieldNames(Index) = Query.Fields(Index).Name
    Next
    
    GetFieldNames = FieldNames()
    
End Function