Sunday, March 26, 2017

Macro to Open Text File

'-----------------------------Macro to Open Text File-----------------------------------'
Sub OpenTextFile_1()

Dim fso As New FileSystemObject
Dim txtfl As TextStream
Dim i, j As Integer
Dim Arr

Application.FileDialog(msoFileDialogOpen).Show          'Selection of text file through file dialogbox
Set txtfl = fso.OpenTextFile(Application.FileDialog(msoFileDialogOpen).SelectedItems(1))    'Intializing text file

'-----------Writing the text file contents in excel file-----------------'
i = 1
j = 1
Do Until txtfl.AtEndOfStream
    Arr = Split(txtfl.ReadLine, ",")
        For i = 1 To UBound(Arr)
            Cells(j, i).Value = Arr(i - 1)
        Next
    j = j + 1
Loop

End Sub



'----------------Another Way to Open Text File
Sub OpenTextFile_2()
Application.FileDialog(msoFileDialogOpen).Show
Workbooks.OpenText Application.FileDialog(msoFileDialogOpen).SelectedItems(1), Tab:=True

Dim i, j As Integer
Dim Arr

j = 1
For i = 1 To Range("A" & Rows.Count).End(xlUp).Row
    Arr = Split(Range("A" & i).Value, ",")
        For j = 1 To UBound(Arr)
            Cells(i, j).Value = Arr(j - 1)
        Next
Next
End Sub

No comments:

Post a Comment

*INTERVIEW QUESTIONS

* Ques 01. What is the difference between ByVal and ByRef and which is default ? Ans-  ByRef : If you pass an argument by reference when...