Hi
I have found a code that i have a little trouble to understand and i hope someone would
be so kind and help me.
1. This macro lets me browse and pick a text file to import.
2. When i pick the file a dialogbox comes up an lets me enter a seperator character.
3. When i have chosed seperator character it imports it to the workbook.
Code:
Sub DoTheImport()
Dim FileName As Variant
Dim Sep As String
FileName = Application.GetOpenFilename(FileFilter:="Text File (*.txt),*.txt")
If FileName = False Then
''''''''''''''''''''''''''
' user cancelled, get out
''''''''''''''''''''''''''
Exit Sub
End If
Sep = Application.InputBox("Enter a separator character.", Type:=2)
If Sep = vbNullString Then
''''''''''''''''''''''''''
' user cancelled, get out
''''''''''''''''''''''''''
Exit Sub
End If
Debug.Print "FileName: " & FileName, "Separator: " & Sep
ImportTextFile FName:=CStr(FileName), Sep:=CStr(Sep)
End Sub
Public Sub ImportTextFile(FName As String, Sep As String)
Dim RowNdx As Long
Dim ColNdx As Integer
Dim TempVal As Variant
Dim WholeLine As String
Dim Pos As Integer
Dim NextPos As Integer
Dim SaveColNdx As Integer
Application.ScreenUpdating = False
'On Error GoTo EndMacro:
SaveColNdx = ActiveCell.Column
RowNdx = ActiveCell.Row
Open FName For Input Access Read As #1
While Not EOF(1)
Line Input #1, WholeLine
If Right(WholeLine, 1) <> Sep Then
WholeLine = WholeLine & Sep
End If
ColNdx = SaveColNdx
Pos = 1
NextPos = InStr(Pos, WholeLine, Sep)
While NextPos >= 1
TempVal = Mid(WholeLine, Pos, NextPos - Pos)
Cells(RowNdx, ColNdx).Value = TempVal
Pos = NextPos + 1
ColNdx = ColNdx + 1
NextPos = InStr(Pos, WholeLine, Sep)
Wend
RowNdx = RowNdx + 1
Wend
EndMacro:
On Error GoTo 0
Application.ScreenUpdating = True
Close #1
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' END ImportTextFile
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
End Sub
everything works great with this but there is 3 things i need help with !
1. My seperator character is always (space) is it possible to change that so it doesnt ask for it (so it does it by default) ?
2. Because textfiles can get pretty large is it possible to get it to read from the last line in reverse (backwards) and stop att first free line):
Ex text file:
aaaa 11111 25622
bbbb 22222 254155
cccc 33333 356998
dddd 44444 532256
aaaa 11111 522546
bbbb 22222 154123
cccc 33333 44512
dddd 55555 11255
(2)
aaaa 11111 5245454
bbbb 22245 556t565
cccc 33333 4454545
dddd 55555 4545454 (1)
Read (1) Last row to (2) Stop att first free row ?
3. When it inserts data in the sheet it puts it in activecell, is it possible to change that to (sheet2) Column A ?
Best regards
Petter
Bookmarks