.Words returns CR-LF

P

Pablo Cardellino

Hi
I have a txt file which is actually a list of words separated by
line-breaks. I open this file and I use the .Words collection to access the
words. While iterating it, the line-breaks (CR LF characters) trigger its
own iterations, as if they were words. So, the control var of the for each
loop assumes the values this way

word1
CRLF
word2
CRLF

and so on.

How could I avoid this, iterating only over the words themselves?

Thanks in advance,
 
J

Jay Freedman

Pablo said:
Hi
I have a txt file which is actually a list of words separated by
line-breaks. I open this file and I use the .Words collection to
access the words. While iterating it, the line-breaks (CR LF
characters) trigger its own iterations, as if they were words. So,
the control var of the for each loop assumes the values this way

word1
CRLF
word2
CRLF

and so on.

How could I avoid this, iterating only over the words themselves?

Thanks in advance,

One way, not really avoiding it but handling it, is to test each "word" and
process it only if it isn't equal to vbCr (or maybe vbCrLf), otherwise skip
to the end of the loop.

Another way is not to open the text file as a document, but instead to use
the VBA functions for dealing with a text file (Open path For Input As #1,
Line Input, etc.) or a TextStream (OpenTextFile, ReadLine, etc.). In both
cases, the input functions ignore the line-ending character. The first one
looks like this:

Sub x()
Dim path As String
Dim oneline As String

path = "c:\docs\words.txt"

On Error Resume Next
Open path For Input As #1
If Err.Number = 0 Then
While Not EOF(1)
Line Input #1, oneline
MsgBox oneline
Wend
End If

Close #1
End Sub

For the second one, you first need to add a reference (through Tools >
References) to the Microsoft Scripting Runtime. Then you can write something
like this:

Sub y()
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Dim fs As FileSystemObject, f As TextStream
Dim path As String
Dim oneline As String

path = "c:\docs\words.txt"

On Error Resume Next
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.OpenTextFile(path, ForReading, TristateFalse)
If Err.Number = 0 Then
oneline = f.readline
While Err.Number <> 62 ' EOF
MsgBox oneline
oneline = f.readline
Wend
f.Close
End If
End Sub

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
 
P

Pablo Cardellino

Thanks, Jay

the vcCr and vbCrLf codes is all I needed.

The other suggestion, on open the file as a stream, isn't useful in this
case, because in other contexts of the code I use the Document object to
perform some operations, such as searches and writings.

Best regards,
Pablo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top