Saturday, April 1, 2017

Convert data from Excel to Text file with comma delimitted

Option Explicit

'Macro to convert excel file into text file

Sub ExcelToTextTransfer2()

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

    ActiveSheet.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)).SpecialCells(xlCellTypeVisible)       'Range selection of filtered visible data
 
    For Each c In rng           'C loop around visible 1st column only (A)
            For j = 1 To Range("A1").End(xlToRight).Column
                TextFile.Write Cells(c.Row, j).Value & ","      'Writing on text file
            Next j
        TextFile.Write vbNewLine      'Line Change
    Next c
 
    TextFile.Close          'Text file closure
 
 
Next mnth
 
MsgBox "done!!"
End Sub

-------------------------------------------------------------------------------------------------------------------

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


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