Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Page History: Linked Tables - Reattaching Programmatically

Compare Page Revisions



« Older Revision - Back to Page History - Current Revision


Page Revision: Tue, Feb 01, 2011, 2:57 PM


Overview

Microsoft Access has a feature called Linked Tables, which are tables that are dynamically linked to another data source. Linked tables are commonly linked to a "back end" database, which is a database containing only data and no code. When distributing the front end counterpart to a new machine, the links to the back end can get broken, because the path to the back end database is stored in each linked table as absolute path. This article contains code that will automatically re-link the linked tables in a database when the database is opened and the links are broken.

Solution

{copytext|vbcode}
Private Sub Form_Load()

    Dim rst As DAO.Recordset
    Dim intNumTables As Integer
    Dim varReturn As Variant
    Dim intI As Integer
    Dim tdf As TableDef
    Dim fd As Office.FileDialog
    Dim vrtSelectedItem As Variant
    Dim sFileName As String
    
    On Error Resume Next
    Set rst = CurrentDb.OpenRecordset("AcctExec", dbOpenDynaset)
    
    'check for failure - the link must be bad.
    If Err <> 0 Then
    
        'get the new location
        Set fd = Application.FileDialog(msoFileDialogFilePicker)
        fd.Title = "Please select the backend database"
        fd.Filters.Clear
        fd.Filters.Add "Access Databases", "*.accdb"
        
        If fd.Show = True Then
            For Each vrtSelectedItem In fd.SelectedItems
                sFileName = vrtSelectedItem
            Next
        End If
        
        'Rebuild the links.  Check for the number of tables first
        intNumTables = CurrentDb.TableDefs.Count
        varReturn = SysCmd(acSysCmdInitMeter, "Relinking tables", intNumTables)
        
        'Loop through all tables.  Reattach those with nonzero-length Connect strings
        intI = 0
        For Each tdf In CurrentDb.TableDefs
        
            'if connect is blank, it's not a linked table
            If Len(tdf.Connect) > 0 Then
            
                intI = intI + 1
                tdf.Connect = ";DATABASE=" & sFileName
                tdf.RefreshLink
                
            End If
            
            varReturn = SysCmd(acSysCmdUpdateMeter, intI)
            
        Next tdf
        
        varReturn = SysCmd(acSysCmdRemoveMeter)
        
    End If
  
End Sub

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.