Importing Text File Into Excel Sheet
Importing Text File Into Excel Sheet
There are many ways you can import Text file to the current sheet. Here are three (including the
method that you are using above)
1. Using a QueryTable
2. Open the text file in memory and then write to the current sheet and finally applying Text To Columns
if required.
3. If you want to use the method that you are currently using then after you open the text file in a new
workbook, simply copy it over to the current sheet using Cells.Copy
Using a QueryTable
Here is a simple macro that I recorded. Please amend it to suit your needs.
Sub Sample()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
)
.Name = "Sample"
.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 = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Open the text file in memory
Sub Sample()
Dim MyData As String, strData() As String
wbO.Sheets(1).Cells.Copy wsI.Cells
wbO.Close SaveChanges:=False
End Sub
FOLLOWUP
You can use the Application.GetOpenFilename to choose the relevant file. For example...
Sub Sample()
Dim Ret
End With
End If
End Sub
I think my answer to my own question here is the simplest solution to what you are trying to do:
1. Select the cell where the first line of text from the file should be.
2. Use the Data/Get External Data/From File dialog to select the text file to import.
3. Format the imported text as required.
4. In the Import Data dialog that opens, click on Properties...
5. Uncheck the Prompt for file name on refresh box.
6. Whenever the external file changes, click the Data/Get External Data/Refresh All button.
Note: in your case, you should probably want to skip step #5.