473,807 Members | 2,884 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Importing Multiple Databases from one folder

1 New Member
Hi,

I am relatively new to Access and VBA. I am trying to import a number of database files (just really want the contents of their tables) from a specified folder into a master table that contains all records and is updated periodically (via imports).
I have tried using a batch process (this limits me to importing specified files) but ideally would like to be able just to import all databases (or just their respective tables) irrespective of the number of files in the folder.
I am using Microsoft Access 2000 on a Windows XP PC. Any ideas or perhaps another way to import would be much appreciated. Either post here or email me at [email removed]

Cheers

James
Feb 19 '07 #1
4 4451
Rabbit
12,516 Recognized Expert Moderator MVP
I have something like this at work. It's not fully automated but it can be with some modifications to the code. I don't get into the office until tomorrow but when I do I'll post my code.
Feb 19 '07 #2
ADezii
8,834 Recognized Expert Expert
Hi,

I am relatively new to Access and VBA. I am trying to import a number of database files (just really want the contents of their tables) from a specified folder into a master table that contains all records and is updated periodically (via imports).
I have tried using a batch process (this limits me to importing specified files) but ideally would like to be able just to import all databases (or just their respective tables) irrespective of the number of files in the folder.
I am using Microsoft Access 2000 on a Windows XP PC. Any ideas or perhaps another way to import would be much appreciated. Either post here or email me at [email removed]

Cheers

James
Here is a Sub-Routine that accepts an Absolute Path to your Database, the Table Name you wish to Import, and the New Table name that you wish to give it. It checks for the prior existance of the Table Name (previous Import), Deletes it if necessary, Imports the Table, then appends all its Records into tblMaster. The major assumption here, of course, is that the Imported Tables as well as the Master, have the same structure. Have fun.
Expand|Select|Wrap|Line Numbers
  1. Public Sub ImportAndAppend(strDBName As String, strTableName As String, strNewTableName As String)
  2. Dim MyTable As TableDef, MySQL As String
  3.  
  4. MySQL = "INSERT INTO tblMaster SELECT " & strNewTableName & ".* FROM " & strNewTableName
  5.  
  6. DoCmd.SetWarnings False
  7.  
  8. For Each MyTable In CurrentDb.TableDefs
  9.   If MyTable.Name = strNewTableName Then
  10.     CurrentDb().TableDefs.Delete strNewTableName
  11.       Exit For
  12.   End If
  13. Next
  14.  
  15.   DoCmd.TransferDatabase acImport, "Microsoft Access", strDBName, acTable, strTableName, strNewTableName, False
  16.  
  17.   DoCmd.RunSQL MySQL
  18.  
  19. DoCmd.SetWarnings True
  20. End Sub
Here are your typical calls:
Expand|Select|Wrap|Line Numbers
  1. Call ImportAndAppend("C:\Test Directory\Test.mdb", "tblEmployee", "tblEmployee2")
  2. Call ImportAndAppend("C:\Pension\Test.mdb", "tblEmployee", "tblEmployeePension")
Feb 19 '07 #3
Rabbit
12,516 Recognized Expert Moderator MVP
Here is my form module. You can tear up this code and set up some sort of loop to append each file. This code right now only appends the file selected by the user. Comments on the code will follow in the next post.

Expand|Select|Wrap|Line Numbers
  1. Option Compare Database
  2. Option Explicit
  3.  
  4. Private Sub but_Append_Click()
  5.  
  6. If IsNull(Month) Or IsNull(Year) Then
  7.     MsgBox "Please Select Month and Year"
  8.     End
  9. End If
  10.  
  11. If IsNull(FileList.Column(0)) Or FileList.Column(0) = "No Files Found." Then End
  12.  
  13. Dim path, npath As String
  14. Dim db As Database
  15. Dim rst As Recordset
  16. Dim PID As Integer
  17. Dim temp As Variant
  18. Dim DateCreated, DataMonth, PName, SName As String
  19.  
  20. Set db = CurrentDb
  21.  
  22. path = Application.CurrentProject.path & "\" & FileList.Column(0)
  23. DoCmd.TransferDatabase acImport, "Microsoft Access", path, acTable, "tbl_MainOut", "tbl_MainOut"
  24. DoCmd.TransferDatabase acImport, "Microsoft Access", path, acTable, "tbl_JobsOut", "tbl_JobsOut"
  25. DoCmd.DeleteObject acTable, "tbl_Main_Backup"
  26. DoCmd.DeleteObject acTable, "tbl_Jobs_Backup"
  27. DoCmd.CopyObject , "tbl_Main_Backup", acTable, "tbl_Main"
  28. DoCmd.CopyObject , "tbl_Jobs_Backup", acTable, "tbl_Jobs"
  29.  
  30. Set rst = db.OpenRecordset("tbl_MainOut")
  31. rst.MoveFirst
  32. temp = rst.GetRows(1)
  33. PID = temp(0, 0)
  34. DoCmd.SetWarnings False
  35. DoCmd.RunSQL "DELETE FROM tbl_Main WHERE PID = " & PID
  36. DoCmd.RunSQL "DELETE FROM tbl_Jobs WHERE PID = " & PID
  37. DoCmd.RunSQL "INSERT INTO tbl_Main SELECT * FROM tbl_MainOut"
  38. DoCmd.RunSQL "INSERT INTO tbl_Jobs SELECT * FROM tbl_JobsOut"
  39. DoCmd.RunSQL "SELECT tbl_CodeProvider.Short, tbl_CodeProvider.Name INTO tbl_CurrentProvider FROM tbl_MainOut INNER JOIN tbl_CodeProvider ON tbl_MainOut.PID = tbl_CodeProvider.PID"
  40. DoCmd.SetWarnings True
  41.  
  42. rst.Close
  43.  
  44. DoCmd.DeleteObject acTable, "tbl_MainOut"
  45. DoCmd.DeleteObject acTable, "tbl_JobsOut"
  46.  
  47. Set rst = db.OpenRecordset("tbl_CurrentProvider")
  48. rst.MoveFirst
  49. temp = rst.GetRows(1)
  50. PName = temp(1, 0)
  51. SName = temp(0, 0)
  52.  
  53. npath = Application.CurrentProject.path & "\Providers\" & SName & "\" & FileList.Column(0)
  54. FileCopy path, npath
  55. db.Close
  56. SetAttr path, vbNormal
  57. Kill path
  58.  
  59. DateCreated = Mid(FileList.Column(0), 22, Len(FileList.Column(0)) - 25)
  60. DataMonth = Month & "/" & Year
  61. DoCmd.SetWarnings False
  62. DoCmd.RunSQL "INSERT INTO tbl_Log VALUES (" & PID & ", '" & DateCreated & "', '" & DataMonth & "', Date())"
  63. DoCmd.SetWarnings True
  64. Check
  65.  
  66. MsgBox "Data for " & PName & " has been appended for " & DataMonth & "."
  67.  
  68. End Sub
  69.  
  70. Private Sub but_Close_Click()
  71. DoCmd.Close acForm, "frm_Append"
  72. End Sub
  73.  
  74. Private Sub Form_Load()
  75. Check
  76. End Sub
  77.  
  78. Function Check()
  79. With Application.FileSearch
  80.     Dim length As Integer
  81.     length = Len(Application.CurrentProject.path) + 2
  82.     .NewSearch
  83.     .LookIn = Application.CurrentProject.path
  84.     .SearchSubFolders = False
  85.     .FileName = "CDCR CCRC-PSC Export"
  86.     .MatchTextExactly = False
  87.     .FileType = msoFileTypeDatabases
  88.  
  89.     If .Execute() > 0 Then
  90.         Dim i As Integer
  91.         Dim Files As String
  92.         Files = "'" & Mid(.FoundFiles(1), length) & "'"
  93.         For i = 2 To .FoundFiles.Count
  94.             Files = Files & ";'" & Mid(.FoundFiles(i), length) & "'"
  95.         Next i
  96.         FileList.RowSource = Files
  97.     Else
  98.         FileList.RowSource = "'No Files Found.'"
  99.     End If
  100. End With
  101. End Function
  102.  
Feb 20 '07 #4
Rabbit
12,516 Recognized Expert Moderator MVP
Expand|Select|Wrap|Line Numbers
  1. Option Compare Database
  2. Option Explicit
  3.  
  4. Private Sub but_Append_Click()
  5.  
  6. If IsNull(Month) Or IsNull(Year) Then
  7.     MsgBox "Please Select Month and Year"
  8.     End
  9. End If
  10.  
FileList is a List Box that is populated using the function Check().
Expand|Select|Wrap|Line Numbers
  1. If IsNull(FileList.Column(0)) Or FileList.Column(0) = "No Files Found." Then Exit Sub
  2.  
  3. Dim path, npath As String
  4. Dim db As Database
  5. Dim rst As Recordset
  6. Dim PID As Integer
  7. Dim temp As Variant
  8. Dim DateCreated, DataMonth, PName, SName As String
  9.  
  10. Set db = CurrentDb
  11.  
FileList.Column (0) refers to the first column of the selected item from the list box. This code assumes that the databases are in the same folder as the consolidation database.
Expand|Select|Wrap|Line Numbers
  1. path = Application.CurrentProject.Path & "\" & FileList.Column(0)
  2. DoCmd.TransferDatabase acImport, "Microsoft Access", path, acTable, "tbl_MainOut", "tbl_MainOut"
  3. DoCmd.TransferDatabase acImport, "Microsoft Access", path, acTable, "tbl_JobsOut", "tbl_JobsOut"
  4. DoCmd.DeleteObject acTable, "tbl_Main_Backup"
  5. DoCmd.DeleteObject acTable, "tbl_Jobs_Backup"
  6. DoCmd.CopyObject , "tbl_Main_Backup", acTable, "tbl_Main"
  7. DoCmd.CopyObject , "tbl_Jobs_Backup", acTable, "tbl_Jobs"
  8.  
This next part of the code does a conditional delete. Here's how our system works. We receive the data from multiple programs each month. Every time they send the data, they send their full data, not just the new records. So each program has a Program ID (PID). When we go to consolidate the data, we delete all the records with that PID and then append the new records we just imported.
Expand|Select|Wrap|Line Numbers
  1. Set rst = db.OpenRecordset("tbl_MainOut")
  2. rst.MoveFirst
  3. temp = rst.GetRows(1)
  4. PID = temp(0, 0)
  5. DoCmd.SetWarnings False
  6. DoCmd.RunSQL "DELETE FROM tbl_Main WHERE PID = " & PID
  7. DoCmd.RunSQL "DELETE FROM tbl_Jobs WHERE PID = " & PID
  8. DoCmd.RunSQL "INSERT INTO tbl_Main SELECT * FROM tbl_MainOut"
  9. DoCmd.RunSQL "INSERT INTO tbl_Jobs SELECT * FROM tbl_JobsOut"
  10. DoCmd.RunSQL "SELECT tbl_CodeProvider.Short, tbl_CodeProvider.Name INTO tbl_CurrentProvider FROM tbl_MainOut INNER JOIN tbl_CodeProvider ON tbl_MainOut.PID = tbl_CodeProvider.PID"
  11. DoCmd.SetWarnings True
  12.  
  13. rst.Close
  14.  
  15. DoCmd.DeleteObject acTable, "tbl_MainOut"
  16. DoCmd.DeleteObject acTable, "tbl_JobsOut"
  17.  
This next part moves the file that was just appended to an archive folder that is composed of their Provider Name (SName).
Expand|Select|Wrap|Line Numbers
  1. Set rst = db.OpenRecordset("tbl_CurrentProvider")
  2. rst.MoveFirst
  3. temp = rst.GetRows(1)
  4. PName = temp(1, 0)
  5. SName = temp(0, 0)
  6.  
  7. npath = Application.CurrentProject.path & "\Providers\" & SName & "\" & FileList.Column(0)
  8. FileCopy path, npath
  9. db.Close
  10. SetAttr path, vbNormal
  11. Kill path
  12.  
This here appends a record into a log that this program last provided us data on some date, This date is a part of the filename as all exports that we receive from the program directors are named using the same convention. "Program Name Export Date Created.mdb". Then we run Check() again to refresh the List Box.
Expand|Select|Wrap|Line Numbers
  1. DateCreated = Mid(FileList.Column(0), 22, Len(FileList.Column(0)) - 25)
  2. DataMonth = Month & "/" & Year
  3. DoCmd.SetWarnings False
  4. DoCmd.RunSQL "INSERT INTO tbl_Log VALUES (" & PID & ", '" & DateCreated & "', '" & DataMonth & "', Date())"
  5. DoCmd.SetWarnings True
  6.  
  7. Check
  8.  
  9. MsgBox "Data for " & PName & " has been appended for " & DataMonth & "."
  10.  
  11. End Sub
  12.  
  13. Private Sub but_Close_Click()
  14. DoCmd.Close acForm, "frm_Append"
  15. End Sub
  16.  
  17. Private Sub Form_Load()
  18. Check
  19. End Sub
  20.  
  21. Function Check()
  22. With Application.FileSearch
  23.     Dim length As Integer
  24.     length = Len(Application.CurrentProject.path) + 2
  25.     .NewSearch
  26.     .LookIn = Application.CurrentProject.path
  27.     .SearchSubFolders = False
  28.     .FileName = "CDCR CCRC-PSC Export"
  29.     .MatchTextExactly = False
  30.     .FileType = msoFileTypeDatabases
  31.  
  32.     If .Execute() > 0 Then
  33.         Dim i As Integer
  34.         Dim Files As String
  35.         Files = "'" & Mid(.FoundFiles(1), length) & "'"
  36.         For i = 2 To .FoundFiles.Count
  37.             Files = Files & ";'" & Mid(.FoundFiles(i), length) & "'"
  38.         Next i
  39.         FileList.RowSource = Files
  40.     Else
  41.         FileList.RowSource = "'No Files Found.'"
  42.     End If
  43. End With
  44. End Function
  45.  
This code is about a month old and I've learned a bit since then. So I'm sure optimizations could be made to it. But it works and you should be able to scrap a lot of it for your purposes.
Feb 20 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

2
2323
by: Sara | last post by:
Hi - I've been reading the posts for a solution to my query, and realize that I should ask an "approch" question as well. We receive our production data from a third party, so my uers import the data from Excel into the appropriate tables. There are 6 different databases that receive data, though 4 of them only get one table each. I have learned how to automate the data import through
5
3187
by: dixie | last post by:
If I sent a user an empty database container - dB with no tables and I needed them to import their tables into it and one of their tables was a hidden table with the prefix Usys, is there any way in code I can get that table imported without them having to go to options and show hidden tables and then import it manually? dixie
2
1825
by: Regnab | last post by:
Just chasing a few ideas for a suitable loop for importing multiple text files. Up until now I have used a Do While Len(strfile) > 0 and moved each file to a different folder after being imported. However this time I want to keep them in the same folder and this loop obviously just goes around in circles. Just wondering what people would use in this situation? Cheers Reg
4
2220
by: Kathie via AccessMonster.com | last post by:
Hello, I have to import monthly, files that were once *.csv but due to commas in addresses, the interface program was changed to dump tab delimited. Now my code is not finding the files in the folder? The code is below - can anyone help? (The files still are named with the extension of *.csv) Function Import_Records() 'On Error GoTo Import_Records_Err 'Delete the all records in MONTHLY_IMPORTS table 'Call...
2
3188
by: Snozz | last post by:
The short of it: If you needed to import a CSV file of a certain structure on a regular basis(say 32 csv files, each to one a table in 32 databases), what would be your first instinct on how to set this up so as to do it reliably and minimize overhead? There are currently no constraints on the destination table. Assume the user or some configuration specifies the database name, server name, and filename+fullpath. The server is SQL...
1
2493
by: penny111 | last post by:
Hi there, I've migrated a database named "crime" from an MS Access database to MySQL 5.0.37 using the MySQL Migration Toolkit 1.1.11. What i want to do is to copy the database folder from C:\Program Files\MySQL\MySQL Server 5.0\data to the same folder on another machine. So i copied the files directly over, ran MySQL and it recognizes the database (i can see the database included in the list) when i type the command mysql> show...
28
19272
by: kkadakia | last post by:
I get a daily excel file for a entire month which I want to transfer into Access at the end of the month. So, there are around 20-25 excel files I get by the end of the month, and I would like to import them into Access using a button. The data contained in the excel files is similar, so there should no formatting issues while importing. I searched through the forums and found the code by mmccarthy for importing excel files. I tried using...
7
7137
by: cannunzi | last post by:
I'm trying to import multiple files in one access table all at once but i keep hitting an error stating incorrect file path. The code below works when i change the * to the exact file name but then it only imports the one file. I would like the code to import all files in the folder into the table. Any suggestions? Sub FuelTaxImport() DoCmd.TransferSpreadsheet acImport, , _ "FuelTaxReport", "C:\FuelTaxReports\*.xls", True,...
0
9720
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9599
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10626
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10374
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6879
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5685
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4330
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3854
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3011
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.