VBA Convert .txt with pipe separator to excel

BKChedlia

New Member
Joined
Jun 15, 2016
Messages
41
I have a code that convert files in folder from .txt (with "|" separator) to xslx, But the code works fine for some files (when I open it in excel), the others are wrong, when I try to import the wring one manually by excel ribbon(Get external data -- > from text), the files are correct.

This is my code :
Code:
Sub tgr()

Const txtFldrPath As String = "C:\...\txtFiles"     
Const xlsFldrPath As String = "C:\excelFiles"     

Dim CurrentFile As String: CurrentFile = Dir(txtFldrPath & "\" & "*.txt")
Dim strLine() As String
Dim LineIndex As Long

Application.ScreenUpdating = False
Application.DisplayAlerts = False
While CurrentFile <> vbNullString
    LineIndex = 0
    Close #1
    Open txtFldrPath & "\" & CurrentFile For Input As #1
    While Not EOF(1)
        LineIndex = LineIndex + 1
        ReDim Preserve strLine(1 To LineIndex)
        Line Input #1, strLine(LineIndex)
    Wend
    Close #1

    With ActiveSheet.Range("A1").Resize(LineIndex, 1)
        .Value = WorksheetFunction.Transpose(strLine)
        .TextToColumns Other:=True, OtherChar:="|"
    End With

    ActiveSheet.UsedRange.EntireColumn.AutoFit
    ActiveSheet.Copy
    ActiveWorkbook.SaveAs xlsFldrPath & "\" & Replace(CurrentFile, ".txt", ".xlsx"), xlOpenXMLWorkbook
    ActiveWorkbook.Close False
    ActiveSheet.UsedRange.ClearContents

    CurrentFile = Dir
Wend
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

the wrong file : drive.google.com/open?id=0B6nhIMB-ueBhRzUtX2dmNl9EWkk && the correct one : drive.google.com/open?id=0B6nhIMB-ueBhdzkzZGJLTVRjNk0
Help plz ?
 

Excel Facts

Format cells as currency
Select range and press Ctrl+Shift+4 to format cells as currency. (Shift 4 is the $ sign).

Forum statistics

Threads
1,221,310
Messages
6,159,176
Members
451,543
Latest member
cesymcox

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top