VBA - 访问数据库表集合

时间:2016-04-20 16:47:57

标签: ms-access access-vba

我有一个sub,它创建了一个链接tabledef的Access数据库对象的新集合。如果代码未重置(仅按F5),子工作时间为1/2,没有错误,但如果首次复位则始终有效。然而,当在另一个模块中调用此子时,它仅在1/2时间工作。任何想法为什么这只能在另一个子调用时只有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 

enter image description here

这是Access给我的错误:

  

“457此键已与此元素相关联   集“

2 个答案:

答案 0 :(得分:1)

你错过了一次刷新:

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

答案 1 :(得分: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显示给立即窗口。当您的代码遇到错误时,您需要了解它发生的原因。