Jon von der Heyden
MrExcel MVP, Moderator
- Joined
- Apr 6, 2004
- Messages
- 10,912
- Office Version
- 365
- Platform
- Windows
Hi All
I am struggling to find methods to delete specific rows and columns from a text file.
I have a text file and I would like to create another text file based on the data within. I would like to build a function to delete multiple rows from the text file {1;2;3;4;5;6;7;8;9;11}. I would also need to know how to count the number of rows so that I can delete e.g. the last 6 rows {87623;87624;87625;87626;87627;87628}.
I would like to be able to do the same with columns.
Finally, all of the data has trailing spaces and I'm not sure what the best method is to trim the data. I have attempted to trim the entire string but it didn't complete it Trim$(strResult).
I have written two functions (below). The first returns a string of the text file data excluding the first n rows. The second writes a string to a text file. The sub routine shows how it is all pulled together, although in reality I would write the output to a new text file.
I am struggling to find methods to delete specific rows and columns from a text file.
I have a text file and I would like to create another text file based on the data within. I would like to build a function to delete multiple rows from the text file {1;2;3;4;5;6;7;8;9;11}. I would also need to know how to count the number of rows so that I can delete e.g. the last 6 rows {87623;87624;87625;87626;87627;87628}.
I would like to be able to do the same with columns.
Finally, all of the data has trailing spaces and I'm not sure what the best method is to trim the data. I have attempted to trim the entire string but it didn't complete it Trim$(strResult).
I have written two functions (below). The first returns a string of the text file data excluding the first n rows. The second writes a string to a text file. The sub routine shows how it is all pulled together, although in reality I would write the output to a new text file.
Code:
Function GetText(ByVal strFileName As String, ByVal lngStartLine As Long) As String
Dim fso As Scripting.FileSystemObject
Dim fts As Scripting.TextStream
Dim strResult As String
Set fso = New Scripting.FileSystemObject
Set fts = fso.OpenTextFile(strFileName, ForReading)
strResult = Replace$(fts.ReadAll, vbCrLf, "", , lngStartLine)
strResult = Mid$(strResult, InStr(strResult, vbCrLf) + 2)
GetText = strResult
fts.Close
Finish:
Set fso = Nothing
Set fts = Nothing
End Function
Function WriteTextData(ByVal strFileName As String, ByVal strData As String)
Dim lngFile As Long
lngFile = FreeFile()
Open strFileName For Output As #lngFile
Print #lngFile, strData
Close #lngFile
End Function
Sub test()
Dim strData As String
Const strPath As String = "H:\FY2010\BI_SOLUTION\SPP_DOWNLOADS\FY10_P1_INCOME_LINE_ITEMS.txt"
strData = GetText(strPath, 9, 2)
WriteTextData strPath, strData
End Sub