gpt4 book ai didi

ms-access - 通过(动态)名称声明一个新的 DAO.Recordset

转载 作者:行者123 更新时间:2023-12-04 19:46:30 25 4
gpt4 key购买 nike

这是一个typical example用于创建 DAO 记录集:

Private Sub OpenOneRecordset()

Dim dbExercise As DAO.Database
Dim rsEmployees As DAO.Recordset

Set dbExercise = CurrentDb
Set rsEmployees = dbExercise.OpenRecordset("Employees")

dbExercise.Close
Set dbExercise = Nothing

End Sub

我想创建多个记录集,每个记录集对应一个在数组中找到的名称:

Public Sub OpenAllRecordsets()

Dim dbExercise As DAO.Database
Set dbExercise = CurrentDb

For Each varTable In arrTables

strRecordsetName = "rst" & varTable

''Above is a string...
''How can I use the string to declare this object?

'' !!!!!!!!! OBVIOUSLY THIS WON'T WORK...
Dim strRecordsetName As DAO.Recordset
Set strRecordsetName = dbExercise.OpenRecordset(varTable)

Next

dbExercise.Close
Set dbExercise = Nothing

End Sub

我看不出如何动态声明名称,然后使用它来制作记录集。我认为这与 TableDefs 的处理方式类似,我在其中调用集合并添加一个成员。你觉得呢?

在第一个发布的答案之后更新:

我在递归函数中使用这些记录集。它有效,但我想减少运行时间。我一直在为所需的新记录重新创建每个记录集。

If nodeThis.hasChildNodes Then

strTable = nodeThis.parentNode.nodeName

Dim rsNewChild As DAO.Recordset ' ***
Set rsNewChild = cnn.OpenRecordset(strTable, dbOpenDynaset) ' ***

rsNewChild.AddNew

'' ...populate fields
For Each ...
strName = nodeThis.nodeName
rsNewChild(strName) = nodeThis.Text
Next

rsNewChild.Update

rsNewChild.close ' ***
Set rsNewChild = Nothing ' ***

End If

但是我知道需要什么记录集,所以我宁愿一开始就把它们全部打开,然后根据需要调用。这样我就可以删除标记为 *** 的行。接下来的问题是如何使用字符串(在函数中可用)来调出给定的记录集。

为了更正确和更有帮助地重申目标:我需要获取一个字符串并使用它来调用所需的记录集:

[ BASED ON STRING ].AddNew 

对于 Barranka 的解决方案,我担心为每次调用循环遍历该数组的资源。但我会试一试,做一些测试。

最佳答案

正如 TableDefsTableDef 对象的内置 Collection 一样,您可以创建自己的 Collection Recordset 对象并按名称引用它们,如下所示:

Dim cdb As DAO.Database, rst As DAO.Recordset, myRecordsets As Collection
Dim testArray(1) As String, tblName As Variant

' test data
testArray(0) = "People"
testArray(1) = "OtherPeople"

' build the collection
Set myRecordsets = New Collection
Set cdb = CurrentDb
For Each tblName In testArray
Set rst = cdb.OpenRecordset(tblName, dbOpenTable)
myRecordsets.Add rst, tblName
Set rst = Nothing
Next

' use the members of the collection
Debug.Print myRecordsets("People").Fields("LastName").Value
myRecordsets("People").MoveNext
Debug.Print myRecordsets("People").Fields("LastName").Value
Debug.Print myRecordsets("OtherPeople").Fields("LastName").Value

Set myRecordsets = Nothing
Set cdb = Nothing

(注意Collections对象的.Add方法的参数是value,key,和方法相反Dictionary 和其他关联数组在添加新条目时倾向于对它们的参数进行排序。)

编辑回复:更新问题

这也行

' add a new record
myRecordsets("OtherPeople").AddNew
myRecordsets("OtherPeople").Fields("LastName").Value = "NewPerson"
myRecordsets("OtherPeople").Update

关于ms-access - 通过(动态)名称声明一个新的 DAO.Recordset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27255841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com