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
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.
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. - Public Sub ImportAndAppend(strDBName As String, strTableName As String, strNewTableName As String)
-
Dim MyTable As TableDef, MySQL As String
-
-
MySQL = "INSERT INTO tblMaster SELECT " & strNewTableName & ".* FROM " & strNewTableName
-
-
DoCmd.SetWarnings False
-
-
For Each MyTable In CurrentDb.TableDefs
-
If MyTable.Name = strNewTableName Then
-
CurrentDb().TableDefs.Delete strNewTableName
-
Exit For
-
End If
-
Next
-
-
DoCmd.TransferDatabase acImport, "Microsoft Access", strDBName, acTable, strTableName, strNewTableName, False
-
-
DoCmd.RunSQL MySQL
-
-
DoCmd.SetWarnings True
-
End Sub
Here are your typical calls: - Call ImportAndAppend("C:\Test Directory\Test.mdb", "tblEmployee", "tblEmployee2")
-
Call ImportAndAppend("C:\Pension\Test.mdb", "tblEmployee", "tblEmployeePension")
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. - Option Compare Database
-
Option Explicit
-
-
Private Sub but_Append_Click()
-
-
If IsNull(Month) Or IsNull(Year) Then
-
MsgBox "Please Select Month and Year"
-
End
-
End If
-
-
If IsNull(FileList.Column(0)) Or FileList.Column(0) = "No Files Found." Then End
-
-
Dim path, npath As String
-
Dim db As Database
-
Dim rst As Recordset
-
Dim PID As Integer
-
Dim temp As Variant
-
Dim DateCreated, DataMonth, PName, SName As String
-
-
Set db = CurrentDb
-
-
path = Application.CurrentProject.path & "\" & FileList.Column(0)
-
DoCmd.TransferDatabase acImport, "Microsoft Access", path, acTable, "tbl_MainOut", "tbl_MainOut"
-
DoCmd.TransferDatabase acImport, "Microsoft Access", path, acTable, "tbl_JobsOut", "tbl_JobsOut"
-
DoCmd.DeleteObject acTable, "tbl_Main_Backup"
-
DoCmd.DeleteObject acTable, "tbl_Jobs_Backup"
-
DoCmd.CopyObject , "tbl_Main_Backup", acTable, "tbl_Main"
-
DoCmd.CopyObject , "tbl_Jobs_Backup", acTable, "tbl_Jobs"
-
-
Set rst = db.OpenRecordset("tbl_MainOut")
-
rst.MoveFirst
-
temp = rst.GetRows(1)
-
PID = temp(0, 0)
-
DoCmd.SetWarnings False
-
DoCmd.RunSQL "DELETE FROM tbl_Main WHERE PID = " & PID
-
DoCmd.RunSQL "DELETE FROM tbl_Jobs WHERE PID = " & PID
-
DoCmd.RunSQL "INSERT INTO tbl_Main SELECT * FROM tbl_MainOut"
-
DoCmd.RunSQL "INSERT INTO tbl_Jobs SELECT * FROM tbl_JobsOut"
-
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"
-
DoCmd.SetWarnings True
-
-
rst.Close
-
-
DoCmd.DeleteObject acTable, "tbl_MainOut"
-
DoCmd.DeleteObject acTable, "tbl_JobsOut"
-
-
Set rst = db.OpenRecordset("tbl_CurrentProvider")
-
rst.MoveFirst
-
temp = rst.GetRows(1)
-
PName = temp(1, 0)
-
SName = temp(0, 0)
-
-
npath = Application.CurrentProject.path & "\Providers\" & SName & "\" & FileList.Column(0)
-
FileCopy path, npath
-
db.Close
-
SetAttr path, vbNormal
-
Kill path
-
-
DateCreated = Mid(FileList.Column(0), 22, Len(FileList.Column(0)) - 25)
-
DataMonth = Month & "/" & Year
-
DoCmd.SetWarnings False
-
DoCmd.RunSQL "INSERT INTO tbl_Log VALUES (" & PID & ", '" & DateCreated & "', '" & DataMonth & "', Date())"
-
DoCmd.SetWarnings True
-
Check
-
-
MsgBox "Data for " & PName & " has been appended for " & DataMonth & "."
-
-
End Sub
-
-
Private Sub but_Close_Click()
-
DoCmd.Close acForm, "frm_Append"
-
End Sub
-
-
Private Sub Form_Load()
-
Check
-
End Sub
-
-
Function Check()
-
With Application.FileSearch
-
Dim length As Integer
-
length = Len(Application.CurrentProject.path) + 2
-
.NewSearch
-
.LookIn = Application.CurrentProject.path
-
.SearchSubFolders = False
-
.FileName = "CDCR CCRC-PSC Export"
-
.MatchTextExactly = False
-
.FileType = msoFileTypeDatabases
-
-
If .Execute() > 0 Then
-
Dim i As Integer
-
Dim Files As String
-
Files = "'" & Mid(.FoundFiles(1), length) & "'"
-
For i = 2 To .FoundFiles.Count
-
Files = Files & ";'" & Mid(.FoundFiles(i), length) & "'"
-
Next i
-
FileList.RowSource = Files
-
Else
-
FileList.RowSource = "'No Files Found.'"
-
End If
-
End With
-
End Function
-
Rabbit 12,516
Recognized Expert Moderator MVP - Option Compare Database
-
Option Explicit
-
-
Private Sub but_Append_Click()
-
-
If IsNull(Month) Or IsNull(Year) Then
-
MsgBox "Please Select Month and Year"
-
End
-
End If
-
FileList is a List Box that is populated using the function Check(). -
If IsNull(FileList.Column(0)) Or FileList.Column(0) = "No Files Found." Then Exit Sub
-
-
Dim path, npath As String
-
Dim db As Database
-
Dim rst As Recordset
-
Dim PID As Integer
-
Dim temp As Variant
-
Dim DateCreated, DataMonth, PName, SName As String
-
-
Set db = CurrentDb
-
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. -
path = Application.CurrentProject.Path & "\" & FileList.Column(0)
-
DoCmd.TransferDatabase acImport, "Microsoft Access", path, acTable, "tbl_MainOut", "tbl_MainOut"
-
DoCmd.TransferDatabase acImport, "Microsoft Access", path, acTable, "tbl_JobsOut", "tbl_JobsOut"
-
DoCmd.DeleteObject acTable, "tbl_Main_Backup"
-
DoCmd.DeleteObject acTable, "tbl_Jobs_Backup"
-
DoCmd.CopyObject , "tbl_Main_Backup", acTable, "tbl_Main"
-
DoCmd.CopyObject , "tbl_Jobs_Backup", acTable, "tbl_Jobs"
-
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. -
Set rst = db.OpenRecordset("tbl_MainOut")
-
rst.MoveFirst
-
temp = rst.GetRows(1)
-
PID = temp(0, 0)
-
DoCmd.SetWarnings False
-
DoCmd.RunSQL "DELETE FROM tbl_Main WHERE PID = " & PID
-
DoCmd.RunSQL "DELETE FROM tbl_Jobs WHERE PID = " & PID
-
DoCmd.RunSQL "INSERT INTO tbl_Main SELECT * FROM tbl_MainOut"
-
DoCmd.RunSQL "INSERT INTO tbl_Jobs SELECT * FROM tbl_JobsOut"
-
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"
-
DoCmd.SetWarnings True
-
-
rst.Close
-
-
DoCmd.DeleteObject acTable, "tbl_MainOut"
-
DoCmd.DeleteObject acTable, "tbl_JobsOut"
-
This next part moves the file that was just appended to an archive folder that is composed of their Provider Name (SName). -
Set rst = db.OpenRecordset("tbl_CurrentProvider")
-
rst.MoveFirst
-
temp = rst.GetRows(1)
-
PName = temp(1, 0)
-
SName = temp(0, 0)
-
-
npath = Application.CurrentProject.path & "\Providers\" & SName & "\" & FileList.Column(0)
-
FileCopy path, npath
-
db.Close
-
SetAttr path, vbNormal
-
Kill path
-
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. -
DateCreated = Mid(FileList.Column(0), 22, Len(FileList.Column(0)) - 25)
-
DataMonth = Month & "/" & Year
-
DoCmd.SetWarnings False
-
DoCmd.RunSQL "INSERT INTO tbl_Log VALUES (" & PID & ", '" & DateCreated & "', '" & DataMonth & "', Date())"
-
DoCmd.SetWarnings True
-
-
Check
-
-
MsgBox "Data for " & PName & " has been appended for " & DataMonth & "."
-
-
End Sub
-
-
Private Sub but_Close_Click()
-
DoCmd.Close acForm, "frm_Append"
-
End Sub
-
-
Private Sub Form_Load()
-
Check
-
End Sub
-
-
Function Check()
-
With Application.FileSearch
-
Dim length As Integer
-
length = Len(Application.CurrentProject.path) + 2
-
.NewSearch
-
.LookIn = Application.CurrentProject.path
-
.SearchSubFolders = False
-
.FileName = "CDCR CCRC-PSC Export"
-
.MatchTextExactly = False
-
.FileType = msoFileTypeDatabases
-
-
If .Execute() > 0 Then
-
Dim i As Integer
-
Dim Files As String
-
Files = "'" & Mid(.FoundFiles(1), length) & "'"
-
For i = 2 To .FoundFiles.Count
-
Files = Files & ";'" & Mid(.FoundFiles(i), length) & "'"
-
Next i
-
FileList.RowSource = Files
-
Else
-
FileList.RowSource = "'No Files Found.'"
-
End If
-
End With
-
End Function
-
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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
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
|
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
|
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
|
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...
|
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...
| |
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...
|
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...
|
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,...
|
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...
|
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,...
|
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...
| |
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,...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |