|
Question : Import Text Files into Access
|
|
Hi Experts,
I have a report program that outputs multiple text files (50+) into a folder. I would like to automate the process of importing all the text files into MS Access and appending the file name as a field in the file. The text files all have the same format: comma delimited records: Account number and worth group.
For example: The first text filename is ABC01.txt I would like it to end up in Access like this:
AccountNo WorthGroup FileName 123456 123 ABC01 123457 123 ABC01 ...
I also need to automatically cycle through all the text files in the folder without user interaction.
Any ideas?
Thanks in advance,
charlie_lv
|
|
Answer : Import Text Files into Access
|
|
try this
Private Sub Command4_Click() Dim strFileName As String, sTableName As String, strPath As String Dim i As Integer, db As DAO.Database Dim fs As Object Set fs = Application.FileSearch With fs .LookIn = "C:\TestText" 'Name of Folder .FileName = "*.txt" If .Execute(SortBy:=msoSortbyFileName, _ SortOrder:=msoSortOrderAscending) > 0 Then MsgBox "There were " & .FoundFiles.Count & _ " file(s) found." For i = 1 To .FoundFiles.Count strPath = .FoundFiles(i) strFileName = Dir(strPath) sTableName = Left$([strFileName], InStr(1, [strFileName], ".") - 1)
DoCmd.TransferText acImportFixed, "savedimportspec", "" & sTableName & "", strPath, False Set db = CurrentDb Dim uSql As String 'alter imported table adding the column NameOfFile db.Execute ("Alter Table " & sTableName & " Add Column NameOfFile Text(25)"), dbFailOnError 'update imported table db.Execute ("Update " & sTableName & " set NameOfFile= '" & sTableName & "'"), dbFailOnError 'append imported table to ImpTextTable uSql = "INSERT INTO ImpTextTable ( AccountNo, WorthGroup, NameOfFile ) " uSql = uSql & "SELECT AccountNo, WorthGroup, NameOfFile " uSql = uSql & "FROM " & sTableName & "" db.Execute uSql, dbFailOnError 'delete imported table db.TableDefs.Delete "" & sTableName & ""
Next i Else MsgBox "There were no files found." End If End With
End Sub
|
|
|
|