I am trying to created test data files. The data is currently in Excel and the widths of the columns have been set to that of the fields within a database. I want to save the Excel file so that the widths of the columns remain. I have tried saving as .prn and this works for some files however .prn is limited to 240 characters per line so any files which have more than this automatically wrap the columns. This is no good as when the file is read the columns are counted therefore the load gets confused.
I have tried saving as .csv and getting rid of the commas however this does not save the column widths.
How can I save the file so that the widths are saved to some sort of text file?
Other info - ultimately I need to change the file so that it is .dat and this is simple enough by changing the file extension.
Thanks in advance
Given the usual way of setting column widths and saving to prn does not work you will have to use VBA to write the file.
Last edited by Andy Pope; 02-22-2010 at 07:50 AM. Reason: fix link
Given the usual way of setting column widths and saving to prn does not work you will have to use VBA to wrhttp://www.exceltip.com/exceltips.phpite the file.
Here is some code to get you started.
Code:Sub ExportFixedWidth() Dim rngData As Range Dim lngCol As Long Dim lngRow As Long Dim strTemp As String Dim intUnit As Integer Dim lngWidths(1 To 3) As Long Dim strValue As String Dim lngPos As Long lngWidths(1) = 10 lngWidths(2) = 20 lngWidths(3) = 300 Set rngData = ActiveSheet.Range("A1").CurrentRegion intUnit = FreeFile Open ThisWorkbook.Path & "\MyFile.dat" For Output As intUnit For lngRow = 1 To rngData.Rows.Count strTemp = "" For lngCol = 1 To rngData.Columns.Count If Len(rngData.Cells(lngRow, lngCol).Value) > 255 Then lngPos = 1 strValue = "" Do While lngPos <= Len(rngData.Cells(lngRow, lngCol).Value) strValue = strValue & rngData.Cells(lngRow, lngCol).Characters(lngPos, 255).Text lngPos = lngPos + 255 Loop Else strValue = rngData.Cells(lngRow, lngCol).Value End If strTemp = strTemp & strValue & Space(lngWidths(lngCol) - Len(strValue)) Next Print #intUnit, strTemp Next Close intUnit End Sub
Thanks for your suggestion Andy. I managed to find a simple macro, details below, yesterday which worked a treat after I edited it to suit my data.
Thanks again,
Lisa
https://www.blogger.com/comment.g?bl...12465133508496
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks