VBA to import text files

bn1974

Registered User.
Local time
Today, 05:40
Joined
Apr 29, 2016
Messages
17
I have several imports that I will be doing every week. Some are excel, some are text files. I need to import the file, delete the data in the existing table, and copy the new data in.

I've figured out how to do it with excel, but I'm stumped with .txt files...

Can I somehow modify this excel import code?

Code:
Dim oExcel As Object
    Dim oBook As Object
    Set oExcel = CreateObject("Excel.Application")
    oExcel.Visible = True
    Set oBook = oExcel.Workbooks.Open("S:\Regulatory\Crew Regulatory Database\Regulatory Downloads\AER\AER Inspections.xls")
    DoCmd.SetWarnings False
    DoCmd.RunSQL "DELETE * FROM AERInspectionT"
    DoCmd.SetWarnings True
    DoCmd.TransferSpreadsheet acImport, , "AERSuspendedWellsT", "S:\Regulatory\Crew Regulatory Database\Regulatory Downloads\AER\AER Inspections.xls", hasfieldnames = False
oBook.Save
oBook.Close
oExcel.Quit
 
on your code you just add one line, after saving the workbook (oBook object):

oBook.Save
' if you have reference to excel object
' the 20 below is equivalent to xlTextWindows
oBook.ActiveSheet.SaveAs "path and file name.txt", 20 'xlTextWindows

'if you like it to be saved as CSV file
oBook.ActiveSheet.SaveAs "path and file name.csv", 23 'xlCSVWindows
oBook.Close
oExcel.Quit
set oBook = nothing
set oExcel = nothing
 
I just had this problem too yesterday!! This is how I solved it and it should help you get on your way!

My design tracks bank account activity but the import process is the same for any project.

Ask if you have more questions on how to get going to the finish line. As of now this only works with .csv but you can change that to .txt files or other ones too. Cheers :D

SOLUTION:

Option Compare Database
Option Explicit



Public Function IMPORT_FILE()

Dim f As Object
Dim i As Integer
Dim sFile As String
'-------------------


On Error GoTo getFP_Err

Set f = Application.FileDialog(3)

With f
.AllowMultiSelect = True
'.AllowMultiSelect = False

.Title = "Please Select the .CSV For Import"

.Filters.Clear
.Filters.Add "Text Files", "*.csv"
'.Filters.Add "All Files", "*.*"


If .Show Then
For i = 1 To .SelectedItems.Count
sFile = .SelectedItems(i)

If Right(sFile, 3) = "CSV" Then
Dim sTable As String
sTable = Mid(sFile, 1 + InStrRev(sFile, "\", , _
vbTextCompare), _
Len(sFile) - 4 - InStrRev(sFile, "\", , vbTextCompare))

sTable = "timp_" & sTable
If IsTableQuery("", sTable) Then
Call DeleteAll(sFile, sTable)
End If
Call GetTextFileData(sFile, sTable)
MsgBox "Import Complete"
End If


Next
End If

End With


getFP_Exit:
Exit Function
getFP_Err:
MsgBox Error$
Resume getFP_Exit

End Function

Function DeleteAll(sFile As String, sTable As String)
Dim sSQL As String

sSQL = "Delete * from " & sTable & ";"
DoCmd.SetWarnings False
DoCmd.RunSQL sSQL
DoCmd.SetWarnings True
End Function

Function GetTextFileData(sFile As String, sTable As String)
Dim blnHasFieldNames As Boolean
Dim strTable As String
Dim strPathfile As String

' Change this next line to True if the first row in CSV worksheet
' has field names

If InStr(sTable, "AMEX") > 0 Or InStr(sTable, "WELLS") > 0 Then
blnHasFieldNames = False
Else
blnHasFieldNames = True
End If

DoCmd.TransferText acImportDelim, , sTable, sFile, blnHasFieldNames

End Function



'********************************************************
' FUNCTION: IsTableQuery()
' SOURCE: https://support.microsoft.com/en-us/kb/113549
' PURPOSE: Determine if a table or query exists.
'
' ARGUMENTS:
' DbName: The name of the database. If the database name
' is "" the current database is used.
' TName: The name of a table or query.
'
' RETURNS: True (it exists) or False (it does not exist).
'
'********************************************************
Public Function IsTableQuery(DbName As String, TName As String) As Integer
Dim Db As Database, Found As Integer, Test As String
Const NAME_NOT_IN_COLLECTION = 3265

' Assume the table or query does not exist.
Found = False

' Trap for any errors.
On Error Resume Next

' If the database name is empty...
If Trim$(DbName) = "" Then
' ...then set Db to the current Db.
Set Db = CurrentDb()
Else
' Otherwise, set Db to the specified open database.
Set Db = DBEngine.Workspaces(0).OpenDatabase(DbName)

' See if an error occurred.
If Err Then
MsgBox "Could not find database to open: " & DbName
IsTableQuery = False
Exit Function
End If
End If

' See if the name is in the Tables collection.
Test = Db.TableDefs(TName).Name
If Err <> NAME_NOT_IN_COLLECTION Then Found = True

' Reset the error variable.
Err = 0

' See if the name is in the Queries collection.
Test = Db.QueryDefs(TName$).Name
If Err <> NAME_NOT_IN_COLLECTION Then Found = True

Db.Close

IsTableQuery = Found

End Function
 
I feel that I may have not explained myself clearly.

Is there code that I can write to import a text file via VBA?

I don't want to use the wizard, as the text file requires some manipulation before it imports (need to delete a row, which I want to write into the code).

Ideally, I'd create a macro from the code, and assign it to a button so my users just have to click 1 button to edit the file and import it into the database.
 
Yes, I have been playing around with it, but can't make it work.
I am new to VBA - I'm still at the "google an example, and edit it to suit me" stage.

Can't find an example to copy. LOL
 
If you will upload a sample of the text file you want to import I'll see if I can write something to get you started.
 
Had this problem a few times and always found it easier to use the transfertext approach.

The easy way is to transfer it all into a table and then do your modifications in that table rather than in the external text file.

Then transfer the data from that table to your real table and delete the contents of the first table.
 
Thanks very much for your help everyone.
I think this will have to be something that I edit manually before importing.
 

Users who are viewing this thread

Back
Top Bottom