【问题标题】:VBA - Access database table collectionVBA - 访问数据库表集合
【发布时间】:2016-04-20 16:47:57
【问题描述】:

我有一个 sub 创建一个新的 Access 数据库对象集合链接 tabledef。如果代码未重置(只需按 F5),则 sub 可以正常工作 1/2 的时间,但如果第一次重置,则始终可以正常工作。然而,当在另一个模块中调用这个 sub 时,它只能再次工作 1/2 的时间。任何想法为什么这只在另一个 sub 中调用时只工作 1/2 时间?

Public Tables As New Collection
Sub SET_VAR()
'##############################################################
'# 1. CREATE PUBLIC COLLECTION OF LINKED TABLES IN DB
'##############################################################
On Error GoTo handlr:
   Dim tdf As TableDef
   Dim db As Database
   Set db = DBEngine(0)(0)
   For Each tdf In db.TableDefs
      If Left(tdf.Connect, 5) = "ODBC;" Then
         Tables.Add tdf, Chr(34) & tdf.Name & Chr(34)
      End If
   Next tdf
   MsgBox "Success. Linked tables public collection created!"
   Exit Sub
handlr:
   MsgBox "Error. Linked tables not added to public collection!"
   End
End Sub 

这是 Access 给我的错误:

"457 此键已与此元素关联 收藏”

【问题讨论】:

  • "457 这个键已经与这个集合的一个元素相关联" 我明白了!
  • @HansUp 成功了!更改 Dim Tables 和 Set Tables = New Collection 工作 %100。谢谢!

标签: ms-access vba


【解决方案1】:

将第一行更改为Public Tables As Collection 然后,在SET_VAR() 中,添加Set Tables = New Collection

Public Tables As Collection
Sub SET_VAR()
On Error GoTo handlr:
   Dim tdf As TableDef
   Dim db As Database
   Set Tables = New Collection
   Set db = DBEngine(0)(0)
   For Each tdf In db.TableDefs
      If Left(tdf.Connect, 5) = "ODBC;" Then
         Tables.Add tdf, Chr(34) & tdf.Name & Chr(34)
      End If
   Next tdf
   MsgBox "Success. Linked tables public collection created!"
   Exit Sub
handlr:
   MsgBox "Error. Linked tables not added to public collection!" & _
        vbCrLf & "(error #" & err.Number & " :" & err.Description & ")"
End Sub 

由于每次程序运行时都会以空的Collection 开始,因此这些更改应该可以消除重复键的问题。

我还在MsgBox 文本中添加了错误编号和描述。如果您不想向用户显示这些详细信息,请Debug.Print 将它们显示到“立即”窗口。当您的代码遇到错误时,您需要了解它发生的原因。

【讨论】:

    【解决方案2】:

    你错过了刷新:

    Set db = DBEngine(0)(0)
    For Each tdf In db.TableDefs
        If Left(tdf.Connect, 5) = "ODBC;" Then
            Tables.Add tdf, Chr(34) & tdf.Name & Chr(34)
        End If
    Next tdf
    db.TableDefs.Refresh
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 2022-07-31
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多