Export Spreadsheet as text file with CSV
A tool purpose is to generate an input for another program or dashboard.
Input files are mostly requested as text .txt file or as excel .xlsx file.
Using a macro we can export or save as one or more spreadsheets from excel .
Save as text file (CSV) program
This program uses two macros that work together:
- First macro does the export of one worksheet as a text file
- Second macro does the separation between columns with “;”
To change the separation form change the Separator = Chr(59) is “;” with any other character (for information about ASCII characters please check HERE)
ExportSheetAsTextFile :
Sub ExportSheetAsTextFile()
'this macro can be used to export spreadsheet into a text file separated by specific character
Dim lr As Long, FileName As Variant, Separator As String, Lastrow As Long
Sheets("Final List").Select
lr = Sheets("Final List").Range("A" & Rows.Count).End(xlUp).Row
FileName = Application.GetSaveAsFilename(InitialFileName:=vbNullString, FileFilter:="Text Files (*.txt),*.txt")
If FileName = False Then
Exit Sub ' user cancelled, get out
End If
Separator = Chr(59)
If Separator = vbNullString Then
Exit Sub ' user cancelled, get out
End If
Debug.Print "FileName: " & FileName, "Separator: " & Separator
ExportToTextFile FName:=CStr(FileName), Sep:=CStr(Separator), _
SelectionOnly:=False, AppendData:=True
End Sub
ExportToTextFile :
Public Sub ExportToTextFile(FName As String, Sep As String, SelectionOnly As Boolean, AppendData As Boolean)
Dim EntireLine As String, CellValue As String
Dim FNum As Integer, ColIndex As Integer, StartCol As Integer, EndCol As Integer
Dim RowIndex As Long, StartRow As Long, EndRow As Long
On Error GoTo EndMacro:
FNum = FreeFile
If SelectionOnly = True Then
With Selection
StartRow = .Cells(1).Row
StartCol = .Cells(1).Column
EndRow = .Cells(.Cells.Count).Row
EndCol = .Cells(.Cells.Count).Column
End With
Else
With ActiveSheet.UsedRange
StartRow = .Cells(1).Row
StartCol = .Cells(1).Column
EndRow = .Cells(.Cells.Count).Row
EndCol = .Cells(.Cells.Count).Column
End With
End If
AppendData = False
If AppendData = True Then
Open FName For Append Access Write As #FNum
Else
Open FName For Output Access Write As #FNum
End If
For RowIndex = StartRow To EndRow
EntireLine = ""
For ColIndex = StartCol To EndCol
If Cells(RowIndex, ColIndex).Value = "" Then
CellValue = Chr(32)
Else
CellValue = Cells(RowIndex, ColIndex).Value
End If
EntireLine = EntireLine & CellValue & Sep
Next ColIndex
EntireLine = Left(EntireLine, Len(EntireLine) - Len(Sep))
Print #FNum, EntireLine
Next RowIndex
EndMacro:
On Error GoTo 0
Close #FNum
End Sub
Leave a Reply
Want to join the discussion?Feel free to contribute!