I am attempting to import a .txt file into Excel via VBA code and then format the content with a text to column command.
The txt file holds content in the following:
You need to Split the data two ways: into lines using the NewLine character, then into cells using |
Note that the line break chacter in your text file may not be vbNewLine
. If this code doesn't split into lines, thats the first place to look.
To complete your code as poseted, try
Sub Sample()
Dim MyData As String
Dim lineData() As String, strData() As String, myFile As String
Dim i As Long, rng As Range
' lets make it a little bit easier for the user
myFile = Application.GetOpenFilename("Text Files (*.txt), *.txt")
Open myFile For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
' Split into wholes line
lineData() = Split(MyData, vbNewLine)
Set rng = Range("A5")
' For each line
For i = 0 To UBound(lineData)
' Split the line
strData = Split(lineData(i), "|")
' Write to the sheet
rng.Offset(i, 0).Resize(1, UBound(strData) + 1) = strData
Next
End Sub
As an alternative, treat the .txt file as, well, Text
Sub Sample()
Dim fn As Integer
Dim MyData As String
Dim lineData As String, strData() As String, myFile As String
Dim i As Long, rng As Range
myFile = Application.GetOpenFilename("Text Files (*.txt), *.txt")
Set rng = Range("A5")
' Lets not rely on Magic Numbers
fn = FreeFile
Open myFile For Input As #fn
i = 1
Do While Not EOF(fn)
Line Input #fn, lineData
strData = Split(lineData, "|")
rng.Cells(i, 1).Resize(1, UBound(strData) + 1) = strData
i = i + 1
Loop
Close #fn
End Sub