Link to home
Create AccountLog in
Avatar of SteveL13
SteveL13Flag for United States of America

asked on

Trying to create new database file and export existing tables (2 of them) to the new database file via VBA code

I am trying to create a new database file and export existing tables (2 of them) to the new database file via VBA code.  This is my code so far.  But I get an error:

Run-time error 3051.  The Microsoft Access database engine cannot open or write to the file 'C:\Database Name.accdb'.  It is already opened exclusively by another user, or you need permission to view and write its data.


Code:

Private Sub cmdArchiveTables_Click()

   Dim ws As Workspace
   Dim db As Database
   Dim LFilename As String
   Dim tblDataHeader As Object
   Dim tblDataDetail As Object

   'Get default Workspace
   Set ws = DBEngine.Workspaces(0)

   'Path and file name for new mdb file
   LFilename = "C:\Database Name.accdb"

   'Make sure there isn't already a file with the name of the new database
   If Dir(LFilename) <> "" Then Kill LFilename

   'Create a new accdb file
   Set db = ws.CreateDatabase(LFilename, dbLangGeneral)

   'Export tables to new database
   DoCmd.TransferDatabase acExport, "Microsoft Access", LFilename, acTable, "tblDataHeader", "tblDataHeader", False
   DoCmd.TransferDatabase acExport, "Microsoft Access", LFilename, acTable, "tblDataDetail", "tblDataDetail", False

   db.Close
   Set db = Nothing
    
End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Rey Obrero (Capricorn1)
Rey Obrero (Capricorn1)
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of Norie
Norie

What happens if you close the new database before you transfer the tables to it?
Create a new accdb file
   Set db = ws.CreateDatabase(LFilename, dbLangGeneral)

   db.Close

   'Export tables to new database
   DoCmd.TransferDatabase acExport, "Microsoft Access", LFilename, acTable, "tblDataHeader", "tblDataHeader", False
   DoCmd.TransferDatabase acExport, "Microsoft Access", LFilename, acTable, "tblDataDetail", "tblDataDetail", False

   
   

Open in new window

Avatar of SteveL13

ASKER

Send it to my desktop and it worked fine.  Thanks again.