you can manually import data from a text file without saving the connection. I can not seem to duplicate this with VBA?
I have a spread sheet into which I will be making many txt imports and I don't need now want all the connections and range names that will be saved to the file.
The code bleow does have a work around that goes back and deletes the connections and range names after the import is complete, I was just wondering if there was a cleaner way?
Option Explicit
Sub Txt_File_Import()
Dim fName As String 'single file being analyzed/moved
Dim fNameL As Integer 'length of fName
Dim NameL As Integer 'length of fname - 4 (.txt)
Dim cName As String 'fname with no extension (connection name)
Dim count As Integer 'number of imports made (used for unique range name)
Dim n As Integer ' loops
Dim rName As String 'range name created by connection
count = 1
fName = Dir(ThisWorkbook.Path & "\*.txt") 'finds all .txt files in this dir
Do While Len(fName) > 0
' generates a unique range name to be deleted later
rName = "range" & Year(Now) & Month(Now) & Day(Now) & _
Hour(Now) & Minute(Now) & Second(Now) & count
'the addition of this counter keeps the name unique, even if ran twice in one second
count = count + 1
' imports data form the current .txt file
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & ThisWorkbook.Path & "\" & fName, _
Destination:=Range("next_name"))
.Name = rName
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = False
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
'moves the active .txt file to an archive dir
Name ThisWorkbook.Path & "\" & fName As ThisWorkbook.Path & "\CustomerInformationLog\" & fName
'strips the ".txt" off the active .txt file
'therefore generating the connection name used in the last import
fNameL = Len(fName)
NameL = fNameL - 4
cName = Left(fName, NameL)
'deletes the connection of the last import
ActiveWorkbook.Connections(cName).Delete
'deletes the range created in the last import
ActiveWorkbook.Names(rName).Delete
fName = Dir
Loop
End Sub
any other suggestions to this code are obviously welcome.
Thanks
Bookmarks