Avatar of SteveL13
SteveL13
Flag 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

Microsoft Access

Avatar of undefined
Last Comment
SteveL13

8/22/2022 - Mon