Sunday, April 2, 2017

Read from Excel to Text File

Option Explicit

'Macro to convert excel file into text file

Sub ExcelToTextTransfer()

Dim fso As New FileSystemObject
Dim TextFile As TextStream
Dim i, j, mnth As Long
Dim rng, c As Range

'------------Phase I

For mnth = 1 To 12              'Loop for month

    Sheet1.AutoFilterMode = False           'Remove existing filter
    Sheet1.Range("A1").AutoFilter field:=4, Criteria1:=Left(MonthName(mnth), 3)    'Autofilter on month on month

'------------Phase II

    Set TextFile = fso.CreateTextFile("C:\Users\Vinay Kumar\Desktop\VBA Classs\01 Apr\" _
                        & Left(MonthName(mnth), 3) & ".txt") 'Creation of text file
   
'------------Phase III
    Set rng = Range(Range("A1"), Range("A1").End(xlDown))       'Range selection of filtered data
   
    For Each c In rng
        If c.EntireRow.Hidden = False Then                      'If cell is visible perform the activity
            For j = 1 To Range("A1").End(xlToRight).Column
                TextFile.Write Cells(c.Row, j).Value & ","      'Writing on text file
            Next j
        End If
        If c.EntireRow.Hidden = False Then TextFile.Write vbNewLine     'Line Change
    Next c
   
    TextFile.Close          'Text file closure
   
   
Next mnth
   
MsgBox "done!!"
End Sub
------------------------------------------------------------------------------------------------------------------------
Option Explicit

Sub ExcelToTextFile()

Dim fso As New FileSystemObject             'Intialisation of file system object
Dim TextFile As TextStream
Dim wb As Workbook
Dim rng, c As Range
Dim i, j, k, mnth As Long

Set wb = ThisWorkbook
ActiveSheet.AutoFilterMode = False

mnth = 1
For k = 1 To 12

Range("A1").AutoFilter field:=4, Criteria1:=Left(MonthName(mnth), 3)
Set rng = ThisWorkbook.Sheets("Sheet1").Range(Range("A1"), Range("A1").End(xlDown)).SpecialCells(xlCellTypeVisible)
    
    Set TextFile = fso.CreateTextFile("C:\Users\Vinay Kumar\Desktop\VBA Classs\01 Apr\" & Left(MonthName(mnth), 3) & ".txt")
    For Each c In rng
        For j = 1 To 10
        
            
            TextFile.Write Cells(c.Row, j).Value & ","
            
    Next j
    
    TextFile.Write vbNewLine
    
    Next
mnth = mnth + 1
TextFile.Close
Next k

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...