Hi I have a text file that I would like to assign to an array and then assign each item in the array to a custom defined variable. When I open the file in notepad, it seems as if the data is on one line and there's about 10 tabs worth of space until the next piece of information.
I use the following code to successfully view the information in a msgbox as MyArray(i).
In my code example, all the information is listed in MyArray(0) and MyArray(1) gives me an error of subscript out of range. The information in the text file seems to appear as if it were delimited by vbCrLf but that does not work either...
Is there a way to trim the spaces from MyArray(0) and then re-assign the individual data to a new array? Here's what the first two pieces of information look like from my file:
967042
144890
Public Function ReadTextFile()
Dim TextFileData As String, myArray() As String, i As Long
Dim strCustomVariable1 As String
Dim strCustomVariable2 As String
'~~> Open file as binary
Open "C:\textfile\DATA-SND" For Binary As #1
'~~> Read entire file's data in one go
TextFileData = Space$(LOF(1))
Get #1, , TextFileData
'~~> Close File
Close #1
'~~> Split the data in seperate lines
myArray() = Split(TextFileData, vbCrLf)
For i = 0 To UBound(myArray())
MsgBox myArray(i)
Next
End Function
Under normal circumstances, I'd suggest that you use Line Input instead:
Open "C:\textfile\DATA-SND" For Input As #1
Do Until EOF(1)
Redim Preserve myArray(i)
Line Input #1, myArray(i)
i = i + 1&
Loop
Close #1
However, you're likely dealing with different end-line characters. You can use your existing code and just change it to use vbCr or vbLf instead of vbCrLf. My method assumes that your end-line characters are vbCrLf.
So for UNIX files:
myArray() = Split(TextFileData, vbLf)
And for old Mac files:
myArray() = Split(TextFileData, vbCr)
Related
In a text file, I want to remove all Carriage Returns (vbCrLf) except those vbCrLf that are preceded by a period (.)
Honestly, no regex is needed.
Open the text file, split the entire text contents on what you want to retain (to create an array), then loop through the array and replace want you don't want during the file rewrite, ensuring to append what you wanted to retain.
For example:
Dim retain : retain = "." & vbCrLf
Dim toss : toss = vbCrLf
With CreateObject("Scripting.FileSystemObject")
Dim txtFile
With .OpenTextFile("C:\TestFile.txt", 1, False)
txtFile = Split(.ReadAll(), retain)
.Close
End With
With .OpenTextFile("C:\NewTestFile.txt", 2, True)
Dim row
For Each row In txtFile
.Write Replace(row, toss, " ") & retain
Next
.Close
End With
End With
Truth be told, VBScript's RegExp Pattern syntax may not be robust enough -- due to lack of look-ahead patterns -- to handle your conditional criteria cleanly with a single pass.
Here is the way how I write file into txt
Dim FileName As String
FileName = "C:\Users\Coda\Desktop\Calendar\file\" & clickDate & ".txt"
Dim Str1 As String, Val1 As Long
Open FileName For Output As #1
Str1 = Text1.Text
MsgBox ("Save")
Write #1, Str1
Close #1
But it automatically add quote in the beginning and end.
Like this
"Test1
Test2
Test3"
Is there any way I can get rid of these quotes?
The short story - use Print instead of Write.
The Write # statement is used to write records with comma-delimited fields to a sequential file. The Write # statement will automatically enclose string fields in quotes and date fields in pound signs.
The Print # statement is used to write formatted strings of data to a sequential file.
To create records in the fixed-width format , you may use following code sample e.g.:
Print #intFooBar, strEmpName; Tab(21); Format$(intDeptNbr, "####"); _
Tab(30); strJobTitle; _
Tab(51); Format$(dtmHireDate, "m/d/yyyy"); _
Tab(61); Format$(Format$(sngHrlyRate, "#0.00"), "#####")
(I'm quite new to vb, but familiar with vba).
I'm trying to find out how to read a text file from bottom to top as:
the text file is updated 'x' period of time; lines being added,
and I need to find the last entry "line" that contains the contains the text "System Pass". However between the last line of the file and the last line that contains the needed string are a lot unnecessary "dump" lines.
With excel I used to import the text file and loop through the rows starting at the bottom and to determine if I had the correct string line with the inStr function. But this doesn't work, or I just simply don't know how to convert the code to vb.
Help is greatly appreciated.
Thanks
Philippe
Here is an example of how to read a txt file into an array and poll through it from bottom to top using instr to search for text:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("c:\temp\test.txt", ForReading)
strText = objTextFile.ReadAll
objTextFile.Close
MyArray = Split(strText, vbCrLf)
For X = Ubound(MyArray) to lbound(MyArray) step -1
If instr(1,MyArray(X),"T") > 0 then
Wscript.Echo MyArray(X)
End if
Next
My Test file contained this:
hello
World
This
Is
Text
The VBS file popped up 2 message boxes, one with "Text" and one with "This"
You can DIM them if you want:
Dim objFSO
Dim objTextFile
Dim X
Dim MyArray
But VBS doesn't support types so don't try Dim X as Long or anything like that.
Hope that helps
I recommend import the data with Excel, you can use NPOI library, with NPOI you can easily read Excel files in .NET.
EDIT:
Read txt files with VB: https://msdn.microsoft.com/en-us/library/yw67h925.aspx
how to change word in text file by VB script (like sed in unix)
You can use the FileSystemObject Object. Some notes:
Set fs = CreateObject("Scripting.FileSystemObject")
sf = "C:\Docs\In.txt"
Set f = fs.OpenTextFile(sf, 1) ''1=for reading
s = f.ReadAll
s = Replace(s, "Bird", "Cat")
f.Close
Set f = fs.OpenTextFile(sf, 2) ''2=ForWriting
f.Write s
f.Close
Following steps: (when tackling a computing problem, divide and conquer!)
Open the text file
Save file contents to string variables
Close the text file!
Search variable for the word
Replace the word(s)
Save the variable as a text file
overwriting old one
With the help of Google, you should be able to search and discover how to achieve all of the above points.
I am trying to split an RTF file into lines (in my code) and I am not quite getting it right, mostly because I am not really grokking the entirety of the RTF format. It seems that lines can be split by \par or \pard or \par\pard or any number of fun combinations.
I am looking for a piece of code that splits the file into lines in any language really.
You could try the specification (1.9.1) (see External Links on the Wikipedia page - which also has a couple of links to examples or modules in several programming languages).
That would most likely give you an idea of the line insertion "words", so you can split the file into lines using a well-defined set of rules rather than taking a guess at it.
Have you come across O'Reilly's RTF Pocket Guide, by Sean M. Burke ?
On page 13, it says
Here are some rules of thumb for putting linebreaks in RTF:
Put a newline before every \pard or \ (commands that are explained in the "Paragraphs" section.
Put a newline before and after the RTF font-table, stylesheet, and other similar constructs (like the color table, decribed later).
You can put a newline after every Nth space, {, or }. (Alternatively: put a newline after every space, {, or } that's after the 60th column.)
Or were you thinking of extracting the plaintext as lines, and doing it whatever the language of the plaintext?
I coded up a quick and dirty routine and it seems to work for pretty much anything I've been able to throw at it. It's in VB6, but easily translatable into anything else.
Private Function ParseRTFIntoLines(ByVal strSource As String) As Collection
Dim colReturn As Collection
Dim lngPosStart As Long
Dim strLine As String
Dim sSplitters(1 To 4) As String
Dim nIndex As Long
' return collection of lines '
' The lines can be split by the following '
' "\par" '
' "\par " '
' "\par\pard " '
' Add these splitters in order so that we do not miss '
' any possible split combos, for instance, "\par\pard" is added before "\par" '
' because if we look for "\par" first, we will miss "\par\pard" '
sSplitters(1) = "\par \pard"
sSplitters(2) = "\par\pard"
sSplitters(3) = "\par "
sSplitters(4) = "\par"
Set colReturn = New Collection
' We have to find each variation '
' We will look for \par and then evaluate which type of separator is there '
Do
lngPosStart = InStr(1, strSource, "\par", vbTextCompare)
If lngPosStart > 0 Then
strLine = Left$(strSource, lngPosStart - 1)
For nIndex = 1 To 4
If StrComp(sSplitters(nIndex), Mid$(strSource, lngPosStart, Len(sSplitters(nIndex))), vbTextCompare) = 0 Then
' remove the 1st line from strSource '
strSource = Mid$(strSource, lngPosStart + Len(sSplitters(nIndex)))
' add to collection '
colReturn.Add strLine
' get out of here '
Exit For
End If
Next
End If
Loop While lngPosStart > 0
' check to see whether there is a last line '
If Len(strSource) > 0 Then colReturn.Add strSource
Set ParseRTFIntoLines = colReturn
End Function