Splitting on Newline?

Err

Active Member
Joined
Nov 16, 2006
Messages
274
Here is the piece of code that is bugging me.

Code:
Public Function Convert_File(from_file As String) As Variant
    
    Dim fso As Object
    Dim fil As Object
    Dim txt As Object
    Dim strtxt As String
    Dim stringArray() As String
    Dim string_arrayPiece() As Variant
    Dim string_arrayE As Variant 'array element
    Dim repost_String As String
    Dim i As Integer

    LastNonEmpty = -1
    repost_String = ""
    Dim n As Long
    
    
    'filesyestem object that we need to manage files
    Set fso = CreateObject("Scripting.FileSystemObject")

    'File that we like to open and read
    Set fil = fso.GetFile(from_file)
    'Opening file as a text string
    Set txt = fil.OpenAsTextStream(1)
    strtxt = txt.ReadAll
    
    'closes TextStream and free the file as we don't need it anymore
    txt.Close
    
    stringArray() = Split(strtxt, vbCrLf)
    
    'get size
    ReDim string_arrayPiece(UBound(stringArray()), 1)
    
    Convert_File = stringArray()



End Function

Here is a sample text file:

Code:
WHEREAS, the Landlord has entered into a Landlord Services Agreement with Rent_insanity.com pursuant to
which Landlord has agreed to accept rent payments from Rent_insanity.com and agreed to pay Rent_insanity.com a fee;
WHEREAS, Rent_insanity.com desires to provide its default reduction services on the Client's behalf, on the
terms set forth herein; and
NOW THEREFORE, in consideration of the mutual covenants expressed herin and for the
good and valuable consideration, the revept and sufficiency of which are hereby acknowledged, and
intending to be legally bound, the parties agree as follows:
1.1. Agency Appointment; Services. Client appoints Rent_insanity.com as its agent to reduce Rent default to its
Landlord in accordance with the terms of this Agreement. Rent_insanity.com will receive funds transferred to
Rent_insanity.com at the direction of and on behalf of the Client and on the date of each month set forth on the
signature page hereto (the 'Rent Transfer Date'), Rent_insanity.com, will transfer to the Landlord, on behalf of the
Client, such funds held by Rent_insanity.com equal to the monthly rent due and payable (the 'Rent Payment')
under the Lease and specified on the Signature Page hereto, subject to the terms and conditions of
this Agreement (the 'Services').


In typical word fashion... each paragraph just drones on until there is an actual carriage return. I would like for this function to split up the entire string into it's individual substrings and hold them as an array... so that I can put them back together again at my leisure.

The problem is that I'm having trouble telling the split function to look for the end of line...
 

Excel Facts

Waterfall charts in Excel?
Office 365 customers have access to Waterfall charts since late 2016. They were added to Excel 2019.
It's not possible to tell (really) where your line breaks are. I get 14 lines when I copy the text you posted. Is that right?

As far as CRLF I think that's two characters, and as far as I know Split will "split" on only one character. I would use LF. In paranoid mode, I would replace all the CRLF's with LF and then split on LF, so I don't have the orphan CR's in the text.
 
Upvote 0
I wonder if this would work better in ms word; or alternately if I open the text file in Excel (which should automatically separate lines into different rows.)

Thanks I'm trying LF now.
There should be 14 lines in the above sample "text" file.
 
Upvote 0
Split was still not working on CRLF.



Uploaded with ImageShack.us

I don't get it. I tried another method:

Code:
Private Function LinesInFile(ByVal file_name As String) As _
    Long
Dim fnum As Integer
Dim lines As Long
Dim one_line As String

    fnum = FreeFile
    Open file_name For Input As #fnum
    Do While Not EOF(fnum)
        Line Input #fnum, one_line
        lines = lines + 1
    Loop
    Close fnum

    LinesInFile = lines
End Function

This function (which others claim to use successfully) counts one line in the multiple lined file...



A solution is to open the file within a workbook and analyze it from there.
This is unsatisfactory from many perspectives:

1) Writing to a workbook is slower
2) The code is now saddled with Excel and is not portable.

On the other hand:

This is incredibly easy to write and maintain:
 
Upvote 0
Try splitting with vbNewLine
Code:
Sub Test()
Dim strArr() As String
Dim fnum As Integer
Dim lines As Long
Dim one_line As String
 
    fnum = FreeFile
    Open file_name For Input As #fnum
    strArr = Split(Input(LOF(fnum), #fnum), vbNewLine)
    Close #fnum    'Close fnum
End Sub
 
Last edited:
Upvote 0
Try splitting with vbNewLine
Code:
Sub Test()
Dim strArr() As String
Dim fnum As Integer
Dim lines As Long
Dim one_line As String
 
    fnum = FreeFile
    Open file_name For Input As #fnum
    strArr = Split(Input(LOF(fnum), #fnum), vbNewLine)
    Close #fnum    'Close fnum
End Sub


If you look at the watched variable -it is empty:

[IMG=http://img813.imageshack.us/img813/2995/screenshot029f.jpg][/IMG]

Uploaded with ImageShack.us

I played with redim a bit but that doesn't seem to be the problem.

Thanks for brainstorming!!
 
Upvote 0
Requires:
VBE > Tools > References > "Microsoft Scripting Runtime" (scrrun.dll)
scrrun.dll is available in any OS later than and including windows XP

Try this:
Code:
    Dim MYFILE$, s$
    MYFILE = "C:\Blarg.txt"
    With New Scripting.FileSystemObject
        With .OpenTextFile(MYFILE, ForReading)
            Do Until .AtEndOfStream
                s = .ReadLine 'Store one line in s
            Loop
        End With
    End With
 
Upvote 0
Thanks again,

Right now I have this work-around which does what I want but is not optimal...

Code:
Public Function Convert_File(pathnamestring As String, filenamestring As String, ByRef stringArray() As Variant) As Long
    
    Dim fso As Object
    Dim fil As Object
    Dim txt As Object
    Dim strtxt As String
    'Dim stringArray() As String
    Dim string_arrayPiece() As Variant
    Dim string_arrayE As Variant 'array element
    Dim repost_String As String
    Dim i As Integer
    Dim j As Long
    Dim from_file As String
    
    from_file = pathnamestring & filenamestring

    LastNonEmpty = -1
    repost_String = ""
    Dim n As Long
    

  '  ReDim stringArray(1 To j) As String
    
    
  '      'filesyestem object that we need to manage files
  '      Set fso = CreateObject("Scripting.FileSystemObject")
  '
  '      'File that we like to open and read
  '      Set fil = fso.GetFile(from_file)
  '      'Opening file as a text string
  '      Set txt = fil.OpenAsTextStream(1)
  '      strtxt = txt.ReadAll
  '
  '      'closes TextStream and free the file as we don't need it anymore
  '      txt.Close
    
    
    
    Workbooks.OpenText filename:=from_file, _
        Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
        xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, Semicolon:=False, _
        Comma:=False, Space:=False, Other:=False, TrailingMinusNumbers:=True
        
sizeOfArray = Cells(65536, 1).End(xlUp).Row

ReDim stringArray(1 To sizeOfArray)

For i = 1 To sizeOfArray
    stringArray(i) = Cells(i, 1).Text
    
Next i

breakere = True 'f9 this

Convert_File = sizeOfArray

Workbooks(filenamestring).Close

End Function

I'm going to work on improving this unit in the future, yet right now I just need to get results (deadline looming)...

I will return to this problem.

Thanks everyone for help!
 
Upvote 0
This worked for me (split on LF) - for a windows environment.
Edit: Note - requires a reference to the Microsoft Scripting Runtime library (recommend convert to late binding once it's all tested...should you employ it...)

Code:
[COLOR="Navy"]Sub[/COLOR] TestIt()
[COLOR="Navy"]Dim[/COLOR] a [COLOR="Navy"]As[/COLOR] [COLOR="Navy"]Variant[/COLOR]
[COLOR="Navy"]Dim[/COLOR] i [COLOR="Navy"]As[/COLOR] [COLOR="Navy"]Long[/COLOR]

    a = Convert_File2("C:\myTemp\whereas.txt")
    [COLOR="Navy"]For[/COLOR] i = 0 [COLOR="Navy"]To[/COLOR] UBound(a)
        [COLOR="Navy"]Debug[/COLOR].[COLOR="Navy"]Print[/COLOR] "|" & a(i) & "|"
    [COLOR="Navy"]Next[/COLOR] i

[COLOR="Navy"]End[/COLOR] [COLOR="Navy"]Sub[/COLOR]

[COLOR="Navy"]Public[/COLOR] [COLOR="Navy"]Function[/COLOR] Convert_File2(sFilePath [COLOR="Navy"]As[/COLOR] String) [COLOR="Navy"]As[/COLOR] [COLOR="Navy"]Variant[/COLOR]
    
    [COLOR="Navy"]Dim[/COLOR] FSO [COLOR="Navy"]As[/COLOR] FileSystemObject
    [COLOR="Navy"]Dim[/COLOR] ts [COLOR="Navy"]As[/COLOR] TextStream
    [COLOR="Navy"]Dim[/COLOR] s [COLOR="Navy"]As[/COLOR] [COLOR="Navy"]String[/COLOR]
    [COLOR="Navy"]Dim[/COLOR] a() [COLOR="Navy"]As[/COLOR] [COLOR="Navy"]String[/COLOR]

    [COLOR="Navy"]Set[/COLOR] FSO = CreateObject("Scripting.FileSystemObject")
    
    [COLOR="Navy"]Set[/COLOR] ts = FSO.OpenTextFile(sFilePath, ForReading, False)
    s = ts.ReadAll
    ts.Close
    [COLOR="Navy"]Set[/COLOR] ts = [COLOR="Navy"]Nothing[/COLOR]
    s = Replace(s, vbCr, "")
    a() = Split(s, vbLf)
    
    Convert_File2 = a()

[COLOR="Navy"]End[/COLOR] [COLOR="Navy"]Function[/COLOR]

Also adapting KPark91's to get the lines into a vba collection worked as well:
Code:
[COLOR="Navy"]Sub[/COLOR] TestIt3()
[COLOR="Navy"]Dim[/COLOR] col [COLOR="Navy"]As[/COLOR] VBA.Collection
[COLOR="Navy"]Dim[/COLOR] i [COLOR="Navy"]As[/COLOR] [COLOR="Navy"]Long[/COLOR]
    
    [COLOR="Navy"]Set[/COLOR] col = [COLOR="Navy"]New[/COLOR] VBA.Collection
    [COLOR="Navy"]Call[/COLOR] Convert_File3(col, "C:\myTemp\whereas.txt")
    [COLOR="Navy"]For[/COLOR] i = 1 [COLOR="Navy"]To[/COLOR] col.Count
        [COLOR="Navy"]Debug[/COLOR].[COLOR="Navy"]Print[/COLOR] "|" & col.Item(i) & "|"
    [COLOR="Navy"]Next[/COLOR] i

[COLOR="Navy"]End[/COLOR] [COLOR="Navy"]Sub[/COLOR]

[COLOR="Navy"]Sub[/COLOR] Convert_File3(ByRef col [COLOR="Navy"]As[/COLOR] VBA.Collection, [COLOR="Navy"]ByVal[/COLOR] sFilePath [COLOR="Navy"]As[/COLOR] String)
[COLOR="Navy"]Dim[/COLOR] FSO [COLOR="Navy"]As[/COLOR] FileSystemObject
[COLOR="Navy"]Dim[/COLOR] ts [COLOR="Navy"]As[/COLOR] TextStream
[COLOR="Navy"]Dim[/COLOR] s [COLOR="Navy"]As[/COLOR] [COLOR="Navy"]String[/COLOR]
[COLOR="Navy"]Dim[/COLOR] i [COLOR="Navy"]As[/COLOR] [COLOR="Navy"]Long[/COLOR]

    [COLOR="Navy"]Set[/COLOR] FSO = CreateObject("Scripting.FileSystemObject")
    [COLOR="Navy"]With[/COLOR] FSO
        [COLOR="Navy"]Set[/COLOR] ts = .OpenTextFile(sFilePath, ForReading)
        [COLOR="Navy"]With[/COLOR] ts
            [COLOR="Navy"]Do[/COLOR] Until .AtEndOfStream
                col.Add .ReadLine, CStr(i)
                i = i + 1
            [COLOR="Navy"]Loop[/COLOR]
        [COLOR="Navy"]End[/COLOR] [COLOR="Navy"]With[/COLOR]
        ts.Close
        [COLOR="Navy"]Set[/COLOR] ts = [COLOR="Navy"]Nothing[/COLOR]
    [COLOR="Navy"]End[/COLOR] [COLOR="Navy"]With[/COLOR]
    
[COLOR="Navy"]End[/COLOR] [COLOR="Navy"]Sub[/COLOR]
 
Last edited:
Upvote 0

Forum statistics

Threads
1,224,599
Messages
6,179,828
Members
452,946
Latest member
JoseDavid

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top