Is there a way to retrieve information from a text file in vba? - excel

I need to save information from a text file into an array. But I dont know what the specific syntax is.
The information from the text file is about 2000 lines, which obviously you cant store within the vba script. The text looks like the below in one
35SLFR0006350
35SLFR0026350
35SLFR0106350
BARSQR1306000
C280BD1016000
C280BD1016000_mitre
C280BD1016000_square
C280FR0006000
C280MU0006000
C280MU0026000
C280SH0006000
C280SH0006000_outer frame
C305BD0006000
C305BD0006000_mitre
C305BD0006000_square
C305BD0016000
C305BD0016000_mitre
C305BD0016000_square
C305BD2006000
C305BD2006000_mitre
C305BD2006000_square
C305FR0006000
C305MU0006000
C305MU0026000
C305MU0046000
C305SH0006000
C305SH0006000_Un E frame
C340BD1006000_mitre
C340BD1006000_Right,Left,Horizontal
C340BD1006000_Right,Left,Vertical
C340BD1006000_square
C340FR00060000
C340MU0006000
C340MU0026000
C340SH0006000

If you want to save your input file as an array you can first read the whole file and save it as one whole string.
You can then use the Split function with the delimiter \n to return an array, where every element corresponds to one line of the file.
Const file As String = "<pathToFile>"
Dim ResultArray() As String
Dim tempString As String
Dim fn As Integer
fn = FreeFile()
Open file For Input As fn
While Not EOF(fn)
Line Input #fn, LineString
tempString = tempString & LineString & "\n"
Wend
ResultArray = Split(tempString, "\n")

Related

Add 'sep=' line to the csv file

The problem is, I want to copy data from .csv file, but excel automatically separates it into columns by comma, I need to separate it by ";".Can I edit csv file using vba code to add 'sep=' at the beginning?
Excel/VBA ignores the separator option if the file has the .csv extension. You have to rename it to set the delimiter. Check out my VBA CSV parser project.
The solution worked for me is to use filesystem object to read csv file and copy it into temporary file with 'sep=' at the first line.
Here is the code:
Function readCsvF(delim as String, fPath as String) As String
Dim sourceFile As Object, objFSO as Object, newTempFile as Object, _
line as String, newName as String
Set objFSO = CreateObject("scripting.FileSystemObject")
Set sourceFile = objFSO.OpenTextFile(fPath)
newName = objFSO.GetParentFolderName(fPath) & "\tempCSVfile.csv"
Set newTempFile = objFSO.CreateTextFile(newName, True)
newTempFile.Writeline("sep=" & delim)
While Not sourceFile.AtEndOfStream
line = sourceFile.Readline
newTempFile.Writeline (line)
Wend
sourceFile.Close
newTempFile.Close
readCsvF = newName
End Function
So what this function does is basically creates new file in which writes first line sep=*'your specified delimiter'* and then copies data from original csv file line by line. This function takes two string parameters: delim is delimiter you want to use and fPath is a path to the csv file, - and returns a path to the new file, so you can open it as workbook and do whatever manipulation you want with it.
Hopefully this will help someone, I really struggled to find the solution, maybe there was any better way, idk.

VBA Excel, when I read from a text file into a (string) variable, why does it not read Carriage return and line feed characters (0d 0a)

I am working on a macro that takes data from a textbox and writes it to a file. The data includes carriage return/Linefeed characters. At a later stage, I need to read the data from the file and put it back in the textbox in exactly the same form. When I do this, the Cr/Lf characters (0d 0a) are missing. I have established that they are written to the file but not read back. I am using the following snippet to write the file:
Print #1, Temstg
Close #1
and reading it using the following snippet:
Do Until EOF(1)
Line Input #1, T
Temstg = Temstg & T
Loop
Close #1
Where am I going wrong
Rob
As said in the comment Line Input considers newline character as the separator for a new line. Here is the documentation.
The following code reads the complete text file in one shot including newline characters.
Sub ReadFIle()
Dim fileName As String: fileName = "C:\temp\yourfile.txt"
Dim fileContent As String
Dim File As Integer: File = FreeFile
Open fileName For Input As #File
fileContent = Input(LOF(File), File)
Close #File
' example how to split the file in lines then
Dim vDat As Variant
vDat = Split(fileContent, vbNewLine)
End Sub
Reading on Input function

Fastest way to transfer array to text file

I have a one dimensional array with more than 3 million items and I would like to transfer it to a text file. I tried a FileSystemObject method, which is not fast enough for me. So I tried to write to cells in a worksheet and export it as txt file, but I am still searching for a faster way to write an array to a txt file.
Please try also Put (and maybe later also Get):
Private Sub TestPut(myArray() as string)
Dim handle As Long
handle = FreeFile
Open Application.Defaultfilepath & "\Whatever.txt" For Binary As #handle
Put #handle, , myArray
Close #handle
End Sub
You may join your array as a single string to prevent unwanted descriptors (see above Put-documentation) and to define CR or CRLF or whatever as delimiter,
but only if the resulting string's length does not exceed 2,147,483,647 bytes:
Put #handle, , Join(myArray, vbCrLf)
Try something like that
FilePath = "C:\output.txt"
Set FileStream = CreateObject("ADODB.Stream")
FileStream.Open
FileStream.Type = 2 'Text
FileStream.Charset = "utf-8"
FileStream.WriteText vba.Strings.Join(YourArray)
FileStream.SaveToFile (FilePath)
FileStream.Close

How to change encoding from UTF-8 to UTF-8-BOM of exported *.txt files from Excel?

Exported text files from Excel are encoded with UTF-8.
An encoding UTF-8-BOM is needed.
I think that in code shall be inserted a row, written like:
Java
?xml version="1.0" encoding="UTF-8"?
Jasperreport CSV UTF-8 without BOM instead of UTF-8
or
HTML5
meta charset="utf-8"
Bad UTF-8 without BOM encoding
Sub export_data()
Dim row, column, i, j As Integer
Dim fullPath, myFile As String
fullPath = "C:\Workspace"
row = 21
column = 5
For i = 1 To column
myFile = Cells(1, i).Value + ".txt"
myFile = fullPath + "/" + myFile
Open myFile For Output As #1
For j = 2 To row
Print #1, Cells(j, i).Value
Next j
Close #1
Next i
End Sub
How can I define and where to put a row, which defines encoding UTF-8-BOM?
Thank You.
Instead of Printing the file line by line, it might be more efficient to
save your selected range as a CSV UTF-8
you might need to change the file type after saving
Use ADO to process the file as UTF-8
Either will add a BOM automatically.
EDIT
If you are unfamiliar, you could perform the save to csv - utf8 process manually with the macro recorder turned on. Then examine what you have recorded and make appropriate edits.
Another way of adding the BOM, in the context of your existing code, would be to write it directly as a byte array to the first line.
For example:
Dim BOM(0 To 2) As Byte 'EF BB BF
BOM(0) = &HEF
BOM(1) = &HBB
BOM(2) = &HBF
Open myFile For Binary Access Write As #1
Put #1, 1, BOM
Close #1
will put the BOM at the beginning of the file.
You should then change the mode in your subsequent Print code to Append.
I suggest you read about the pros and cons of using Print vs Write
You should also read about declaration statements. In yours, only the last variable on each line is being declared as the specified type; the preceding variables are being implicitly declared as being of type Variant.

Retrieving last line of a txt file with a VBscript

Before all, I want to say that I am not a programmer, so this may be basic for some people but surely not for me!!
The task that I want to accomplish is to retrieve some characters of a data file that is imported automatically from a server.
Data is stored in lines in a CSV or tabbed .txt file, each line consists of date and some numeric values. The format is always the same, only the file grows in one line each time a new value is entered.
What I need the script to do, is open that file (wich adress is known and constant) search for the last line, and then extract a string from that line and write it on a different .TXT file, from where I can import it to another specific software as a raw value.
The part in the middle (extracting string) is fairly simple, but opening and isolating the last line is far too much for me.
Thanks everybody for helping!
dim path
path = "fileName.txt"
otherOption(path)
function otherOption(fileName)
const read = 1
dim arrFileLines()
set objArgs = CreateObject("scripting.FileSystemObject")
if objArgs.FileExists(fileName) then
set objFile = objArgs.OpenTextFile(fileName,read)
i=0
do until objFile.AtEndOfStream
redim preserve arrFileLines(i)
arrFileLines(i) = objFile.ReadLine
i = i + 1
loop
objFile.Close
end if
wscript.Echo arrFileLines(i-1)
end function

Resources