PDA

View Full Version : Text File Import w/ Variable File Name



jmartineau
05-06-2014, 08:37 AM
Hello,
I want the user to be able to select any text file from the file directory and have that be imported into Excel. I am trying to have the windows explorer window open, have the user select a text file (needs to be variable so they can choose from a variety), and then that text file will be delimited by the symbol "|" and be placed in cell a3. Below is the code i have so far. The code is running but it won't place the text in the worksheet; i don't think it's recognizing the file name.

Sub SelectFile()
'Ask which file to copy
x = Application.GetOpenFilename( _
FileFilter:="Text Files (*.txt*), *.txt*", _
Title:="Choose File to Copy", MultiSelect:=False)

'check in case no files were selected
If x = "False" Then Exit Sub

With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & x & ".txt", Destination:=Range("$A$3"))
.Name = "x"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "|"
.TextFileColumnDataTypes = Array(2, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub

Any help would be greatly appreciated! Thank you!

snb
05-06-2014, 09:04 AM
Please, use code tags !!


Sub M_snb()
With Application.FileDialog(msoFileDialogFilePicker)
.Filters.Add "textfiles", "*.txt", 1
.FilterIndex = 1
.Show
Workbooks.OpenText .SelectedItems(1), , , , , , 0, 0, 0, 0, -1, "|"
End With
End Sub