2013-03-15 129 views

回答

2

下面的VBA代碼將創建的PostgreSQL與DSN的連接鏈接的表...

Sub linkTo_PostgreSQL() 
    createLinkedTable_PostgreSQL "public.table1" 
    ' repeat as necessary... 
End Sub 

Sub createLinkedTable_PostgreSQL(PostgreSQL_tableName As String) 
    Dim cdb As DAO.Database, tbd As DAO.TableDef 
    Set cdb = CurrentDb 
    Set tbd = New DAO.TableDef 

    tbd.Connect = "ODBC;Driver={PostgreSQL ODBC Driver(UNICODE)};Server=localhost;Port=5432;Database=linkedDB;Uid=pgUser1;Pwd=pgUser1password;" 
    tbd.SourceTableName = PostgreSQL_tableName 
    tbd.Name = Replace(PostgreSQL_tableName, ".", "_", 1, -1, vbTextCompare) ' e.g. "public.table1"->"public_table1" 
    tbd.Attributes = dbAttachSavePWD 

    cdb.TableDefs.Append tbd 
    Set tbd = Nothing 
    Set cdb = Nothing 
End Sub 

下面的代碼將刷新該鏈接,任何現有的PostgreSQL的鏈接表:

Sub refreshLinked_PostgreSQL() 
    Dim cdb As DAO.Database, tbd As DAO.TableDef 
    Set cdb = CurrentDb 
    For Each tbd In cdb.TableDefs 
     If tbd.Connect Like "ODBC;Driver={PostgreSQL*" Then 
      Debug.Print "Refreshing [" & tbd.Name & "] ..." 
      tbd.RefreshLink 
     End If 
    Next 
    Debug.Print "Done." 
    Set tbd = Nothing 
    Set cdb = Nothing 
End Sub 
+0

非常感謝Thopson先生。還有一個問題,是否有一種簡單的方法,如果表已經鏈接並刷新它們 – Britto 2013-03-16 16:55:00

+0

我編輯了我的答案以添加代碼來刷新現有鏈接。 – 2013-03-16 17:43:53