ACCESS中重新定位鏈接表二步走

字號:

假設(shè)前臺數(shù)據(jù)庫文件名為frontBase.mdb
    后臺數(shù)據(jù)庫文件名為backData.mdb
    frontBase當(dāng)中有鏈接表tbl1, tbl2, tbl3, …,鏈接到backData.mdb中
    首先我們要在前臺數(shù)據(jù)庫文件的啟動窗體加載事件中判斷鏈接是否正確
    方法是打開任意一個鏈接表,假設(shè)為tbl1,代碼如下:
    Public Function CheckLinks() As Boolean
    ’ 檢查到后臺數(shù)據(jù)庫的鏈接;如果鏈接存在且正確的話,返回 True ?! ?BR>    Dim dbs As Database, rst As DAO.Recordset  
    Set dbs = CurrentDb()
    ’ 打開鏈接表查看表鏈接信息是否正確。
    On Error Resume Next
    Set rst = dbs.OpenRecordset(“tbl1”)
    rst.Close
    ’ 如果沒有錯誤,返回 True 。
    If Err = 0 Then
    CheckLinks = True
    Else
    CheckLinks = False
    End If  
    End Function
    啟動窗體的加載事件:
    Private Sub FORM_Load()
    If CheckLinks = False then
    Docmd.OpenFORM “frmConnect”
    End If
    End Sub
    frmConnect 連接窗體如下圖
    [img]f:\\m.bmp[/img]
    接下來的事情就是如何刷新鏈接表了。
    上面的窗體右邊的按鈕是用用來調(diào)用API打開文件對話框,具體代碼如下:
    Declare Function GetOpenFileName Lib \"comdlg32.dll\" Alias \"GetOpenFileNameA\" (pOpenfilename As OPENFILENAME) As Boolean
    Type OPENFILENAME
    lStructSize As Long
    hwndOwner As Long
    hInstance As Long
    lpstrFilter As String
    lpstrCustomFilter As String
    nMaxCustFilter As Long
    nFilterIndex As Long
    lpstrFile As String
    nMaxFile As Long
    lpstrFileTitle As String
    nMaxFileTitle As Long
    lpstrInitialDir As String
    lpstrTitle As String
    flags As Long
    nFileOffset As Integer
    nFileExtension As Integer
    lpstrDefExt As String
    lCustData As Long
    lpfnHook As Long
    lpTemplateName As String
    End Type
    Private Sub FileOpen_Click()
    Dim ofn As OPENFILENAME
    Dim rtn As String
    ofn.lStructSize = Len(ofn)
    ofn.hwndOwner = Me.hwnd
    ofn.lpstrFilter = \"數(shù)據(jù)庫文件 (*.mdb)\" & vbNullChar & \"*.mdb\"
    ofn.lpstrFile = Space(254)
    ofn.nMaxFile = 255
    ofn.lpstrFileTitle = Space(254)
    ofn.nMaxFileTitle = 255
    ofn.lpstrInitialDir = CurrentProject.Path
    ofn.lpstrTitle = \"后臺數(shù)據(jù)文件為\"
    ofn.flags = 6148
    rtn = GetOpenFileName(ofn)
    FileName.SetFocus
    If rtn = True Then
    FileName.Text = ofn.lpstrFile
    FileName.Text = FileName.Text
    OK.Enabled = True
    Else
    FileName.Text = \"\"
    End If
    End Sub
    連接按鈕刷新鏈接表 ,代碼如下:
    Private Sub OK_Click()
    Dim tabDef As TableDef
    For Each tabDef In CurrentDb.TableDefs
    If Len(tabDef.Connect) > 0 Then
    tabDef.Connect = \";DATABASE=\" & Me.FileName.Text & \";PWD=\" + 后臺數(shù)據(jù)庫密碼
    tabDef.RefreshLink
    End If
    Next
    MsgBox \"連接成功!\"
    DoCmd.Close acFORM, Me.Name
    End Sub
    其實很簡單只有兩步,判斷鏈接是否正確和刷新鏈接表。