2013-10-21 85 views
1

我有60個具有相同數據庫結構的MS Access文件。我想從兩個與每個數據庫相關的表中獲取數據,以便從這60個文件中創建一個包含所有記錄的單個數據庫。有沒有簡單的方法來合併所有這些MS Access文件?女士訪問合併多個訪問文件表

回答

3

如果我正確地理解了你,你將在60個數據庫文件中分佈相同的表格,並且您正在尋找一種自動進行聚合的方法。

有幾種不同的方法可以做到這一點。這可能取決於你的情況。我已經演示了兩種不同的方法。

第一種方法很簡單。它只是構建一個靜態查詢,將數據庫名稱替換爲每個查詢。如果你的具體情況過於簡單 - 那麼這應該是個訣竅。

第二種方法使用DAO打開每個數據庫中的每個表並將數據寫入當前數據庫。如果您有一次性異常並需要添加一些智能,則此方法非常有用。

Public Sub SimpleCombine() 

    Dim DBFileList As Collection 
    Dim DBPath As String 
    Dim ForeignTableName As String 
    Dim LocalTableName As String 
    Dim dbfile As Variant 

    ' Configure 
    Set DBFileList = New Collection 
    DBFileList.Add "Test1.accdb" 
    DBFileList.Add "Test2.accdb" 
    DBPath = CurrentProject.Path ' (No Trailing Backslash) 
    ForeignTableName = "Fruit" 
    LocalTableName = "Fruit" 

    For Each dbfile In DBFileList 
     querystr = "INSERT INTO Fruit (FruitName, FruitValue) " & _ 
       "SELECT FruitName, FruitValue " & _ 
       "FROM Fruit IN '" & DBPath & "\" & dbfile & "'" 
     Debug.Print "Transferring Data From " & dbfile 
     CurrentDb.Execute querystr 
     DoEvents 
    Next 
End Sub 

例2

Public Sub DAOCombine() 

    Dim DBFileList As Collection 
    Dim DBPath As String 
    Dim ForeignTableName As String 
    Dim LocalTableName As String 
    Dim db As DAO.Database 
    Dim rst, drst As DAO.Recordset 
    Dim fld As DAO.Field 

    ' Configure 
    Set DBFileList = New Collection 
    DBFileList.Add "Test1.accdb" 
    DBFileList.Add "Test2.accdb" 
    DBPath = CurrentProject.Path ' (No Trailing Backslash) 
    ForeignTableName = "Fruit" 
    LocalTableName = "Fruit" 

    Set drst = CurrentDb.OpenRecordset(LocalTableName) 
    For Each dbfile In DBFileList 
    Debug.Print "Transferring Data From " & dbfile 
    Set db = DBEngine.Workspaces(0).OpenDatabase(DBPath & "\" & dbfile) 
    Set rst = db.OpenRecordset(ForeignTableName) 

    Do Until rst.EOF 
     drst.AddNew 
     For Each fld In rst.Fields 
     If (fld.Attributes And dbAutoIncrField) = dbAutoIncrField Then 
      ' We have an autonumber field - lets skip 
     Else 
      drst.Fields(fld.Name).Value = fld.Value 
     End If 
     Next 
     drst.Update 
     rst.MoveNext 
    Loop 
    rst.Close 
    DoEvents 
    Next 
    drst.Close 

    Set rst = Nothing 
    Set drst = Nothing 
End Sub 

你需要的代碼以適應您的具體情況 - 但它應該做的伎倆。

+0

感謝您的回覆 – sanjay