为什么在currentdb.tabledefs.append

时间:2018-12-17 07:27:45

标签: sql-server ms-access access-vba

我试图在Access中使用DSN减少与VBA的连接来创建链接表。我发现this在线链接真的很有帮助。这是链接中的代码:

'//Name     :   AttachDSNLessTable
'//Purpose  :   Create a linked table to SQL Server without using a DSN
'//Parameters
'//     stLocalTableName: Name of the table that you are creating in the current database
'//     stRemoteTableName: Name of the table that you are linking to on the SQL Server database
'//     stServer: Name of the SQL Server that you are linking to
'//     stDatabase: Name of the SQL Server database that you are linking to
'//     stUsername: Name of the SQL Server user who can connect to SQL Server, leave blank to use a Trusted Connection
'//     stPassword: SQL Server user password
Function AttachDSNLessTable(stLocalTableName As String, stRemoteTableName As String, stServer As String, stDatabase As String, Optional stUsername As String, Optional stPassword As String)
    On Error GoTo AttachDSNLessTable_Err
    Dim td As TableDef
    Dim stConnect As String

    For Each td In CurrentDb.TableDefs
        If td.Name = stLocalTableName Then
            CurrentDb.TableDefs.Delete stLocalTableName
        End If
    Next

    If Len(stUsername) = 0 Then
        '//Use trusted authentication if stUsername is not supplied.
        stConnect = "ODBC;DRIVER=SQL Server;SERVER=" & stServer & ";DATABASE=" & stDatabase & ";Trusted_Connection=Yes"
    Else
        '//WARNING: This will save the username and the password with the linked table information.
        stConnect = "ODBC;DRIVER=SQL Server;SERVER=" & stServer & ";DATABASE=" & stDatabase & ";UID=" & stUsername & ";PWD=" & stPassword
    End If
    Set td = CurrentDb.CreateTableDef(stLocalTableName, dbAttachSavePWD, stRemoteTableName, stConnect)
    CurrentDb.TableDefs.Append td
    AttachDSNLessTable = True
    Exit Function

AttachDSNLessTable_Err:

    AttachDSNLessTable = False
    MsgBox "AttachDSNLessTable encountered an unexpected error: " & Err.Description

End Function

如您所见,每个tabledef都使用结尾添加

CurrentDb.TableDefs.Append td

为我传递的代码没有任何错误。但是这些表没有出现在我的Access中。只有当我压缩并修复数据库后,表格才出现。我不知道为什么会这样。

1 个答案:

答案 0 :(得分:3)

将对象附加到集合之后,您必须刷新集合:CurrentDb.TableDefs.Refresh

并在数据库窗口中查看图标:Application.RefreshDatabaseWindow

  

RefreshDatabaseWindow方法更新数据库窗口(数据库   窗口:在Access 2003及更早版本中,当   数据库或项目已打开。它显示用于创建新的快捷方式   数据库对象并打开现有对象。在更高版本中   在数据库对象(数据库)之后被导航窗格替换。   对象:Access数据库包含表,查询,   表单,报表,页面,宏和模块。一个Access项目包含   对象,例如表单,报表,页面,宏和模块。)   创建,删除或重命名。