How can I link a table from one MS Access Database (*.mdb or *.accdb) to another Access database in VBA?
Basically I just was to use VBA to replicate what the External Data wizard does.
I've googled this and I see many examples of how to update or relink tables and many examples of linking to SQL databases, but very few of simple linking tables between Access databases.
In the File name text box, type the name of the source database or click Browse to display the File Open dialog box. Click Link to the data source by creating a linked table, and then click OK. The Link Tables dialog box opens. In the Link Tables dialog box, select the tables you want to link to.
Open your Microsoft Access database. Select the External Data tab in the ribbon. Expand the New Data Source drop-down and select From Other Sources, then select ODBC Dababase. In the Get External Data - ODBC Database dialog box, select Link to the data source by creating a linked table.
Like macros, VBA lets you add automation and other functionality to your Access application. You can extend VBA by using third-party controls, and you can write your own functions and procedures for your own specific needs.
No need to import tables (linking is enough), querying linked tables will process the query where the access database is located then passing the filters in your where clause to you original server to retreive the results.
You can use the DoCmd.TransferDatabase Method to create a link to a table in another Access database.
DoCmd.TransferDatabase TransferType:=acLink, _
DatabaseType:="Microsoft Access", _
DatabaseName:="C:\share\Access\Example Database.accdb", _
ObjectType:=acTable, _
Source:="Addresses", _
Destination:="Addresses_link"
I included the option names hoping that would make it easier to track which option is which. But if that seems too verbose, you can omit the option names and do it all on one line:
DoCmd.TransferDatabase acLink, "Microsoft Access", "C:\share\Access\Example Database.accdb", acTable , "Addresses", "Addresses_link"
It's actually pretty easy--you just create a new tabledef and set its .connect property to an ODBC connection string that links to the other Access database.
Private Function LinkTable(LinkedTableName As String, TableToLink As String, connectString As String) As Boolean
Dim tdf As New dao.TableDef
On Error GoTo LinkTable_Error
With CurrentDb
.TableDefs.Refresh
Set tdf = .CreateTableDef(LinkedTableName)
tdf.Connect = connectString
tdf.SourceTableName = TableToLink
.TableDefs.Append tdf
.TableDefs.Refresh
End With
Set tdf = Nothing
End Function
The connection string would look something like this (taken from connectionstrings.com):
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb;Persist Security Info=False;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With