There are many ways you can import Text file to the current sheet. Here are three (including the method that you are using above)
- Using a QueryTable
- Open the text file in memory and then write to the current sheet and finally applying Text To Columns if required.
- 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
Open "C:\Sample.txt" For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
End Sub
Once you have the data in the array you can export it to the current sheet.
Using the method that you are already using
Sub Sample()
Dim wbI As Workbook, wbO As Workbook
Dim wsI As Worksheet
Set wbI = ThisWorkbook
Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import
Set wbO = Workbooks.Open("C:\Sample.txt")
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
Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")
If Ret <> False Then
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & Ret, Destination:=Range("$A$1"))
'~~> Rest of the code
End With
End If
End Sub