Thursday, 22 October 2009

EXCEL: Convert xls to txt, csv

Open the Excel file and paste this code into the Source code. Change file type, delimiter and location in the DoTheExport() funtion

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ExportToTextFile' This exports a sheet or range to a text file, using a' user-defined separator character.''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Sub DoTheExport() ExportToTextFile FName:="C:\HRDW\200908.txt", Sep:="~", _ SelectionOnly:=False, AppendData:=TrueEnd Sub
Public Sub ExportToTextFile(FName As String, _ Sep As String, SelectionOnly As Boolean, _ AppendData As Boolean)
Dim WholeLine As StringDim FNum As IntegerDim RowNdx As LongDim ColNdx As IntegerDim StartRow As LongDim EndRow As LongDim StartCol As IntegerDim EndCol As IntegerDim CellValue As String
Application.ScreenUpdating = FalseOn 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 WithElse With ActiveSheet.UsedRange StartRow = .Cells(1).Row StartCol = .Cells(1).Column EndRow = .Cells(.Cells.Count).Row EndCol = .Cells(.Cells.Count).Column End WithEnd If
If AppendData = True Then Open FName For Append Access Write As #FNumElse Open FName For Output Access Write As #FNumEnd If
For RowNdx = StartRow To EndRow WholeLine = "" For ColNdx = StartCol To EndCol If Cells(RowNdx, ColNdx).Value = "" Then CellValue = Chr(34) & Chr(34) Else CellValue = Cells(RowNdx, ColNdx).Text End If WholeLine = WholeLine & CellValue & Sep Next ColNdx WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep)) Print #FNum, WholeLineNext RowNdx
EndMacro:On Error GoTo 0Application.ScreenUpdating = TrueClose #FNum
End Sub''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' END ExportTextFile''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

No comments:

Post a Comment