Retrieving last line of a txt file with a VBscript - string

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

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.

Search txt and csv files for string using Excel VBA without opening files

I have a text file that is automatically generated from a machine. The machine writes the txt file in "chunks" (sorry I don't know the exact terminology). I need to pull data from this txt file, but I need the txt file to be finished before pulling data from it. I found a solution to verify that the machine has finished writing to the file... It is not as elegant as i had hoped, but seems to do the trick. Excel VBA opens a command prompt, the command prompt uses a Find command to find the string "End of Report"... This is basically one of the last lines of the txt file and pretty safe to assume the txt file is finished after this is found. This code runs in a loop 1000 times, every 10 seconds, until it finds this string or reaches 1000 tries...
The issue is that "result" returns some other characters besides just "End of Report" this is further complicated by the fact that I am attempting to run this on some csv files too... and "result" returns some additional characters also, but different from the ones returned from the txt files. For example, if I check the length of "result"... The length comes back as 43 on one file and 48 on another file... I think it is counting the file path + "End of Report" + a few more characters?
Anyways, I don't really need the "result"... I really only need a "true" / "false" if "Find" found "End of Report" or not... How can I accomplish this? Is there a different better way to do this? I am not familiar with command prompt programming.
Note: It is important that I search these files without opening them.
Sub test()
Dim SearchStr As String
Dim cmdLine As Object
Dim result As String
Dim FilePath As String
FilePath = "D:\test2.txt"
SearchStr = """End of Report"""
Set cmdLine = CreateObject("WScript.Shell")
result = cmdLine.Exec("%comspec% /C Find " & SearchStr & " " & Chr(34) & FilePath & Chr(34)).STDOut.ReadAll
Debug.Print (result)
End Sub
I am not really an expert in command line, but what I would do is export the result of the FIND command to a file, like here
Then I would check in your VBA code how many rows are in the file (either clean the file before, or check the number of rows before the export is done).
If the number of rows meets the criteria (probably 2 or more rows instead of 1), then you can set the flag to True.

How to know numerically the last saved file name

I am creating and saving .ini files in Excel. The files need to follow a specific naming convention that increments by 1 each time a file is created. Not all the files will be created in Excel, some will be done in a separate program. Is there a way to read the saved files in their folder to know which number is next?
For example there are files named exampleFile1.ini through exampleFile63.ini. From Excel using VBA or other means can I see that exampleFile63.ini was the last file and name the next exampleFile64.ini?
Thank you. I'm very new if thats not obvious.
This function will return the next available .INI file name:
Private Function GetNextFile() As String
Dim i As Long
Dim fileName As String
For i = 1 To 1000
' Update Path and File Name prefix below to where your .INI files will be stored.
fileName = "d:\path\exampleFile" & i & ".ini"
If Dir(fileName) = "" Then
GetNextFile = fileName
Exit Function
End If
Next
End Function
Call it like this:
Dim NextIniFile As String
NextIniFile = GetNextFile()

Find last row in CSV database from Excel VBA

I am reading a .csv database in excel, because I am using an external database.
I dont want to copy anything into the excel application, I either want to read from the database(and maybe change some values), or add to it.
I have a textbox in a userform that should get the value of the last entry in "column" A(A reference number), and add one to it(this is for the next entry in the database).
I want to find the last row in a semicolon split CSV database using excel VBA.
Here is what I have so far:
Dim FilePath As String
FilePath = "L:\database.csv"
Open FilePath For Input As #1
Do While Not EOF(1)
linenumber = linenumber + 1
Line Input #1, Line
arrayOfElements = Split(Line, ";")
elementnumber = 0
testValue = arrayOfElements(0)
If testValue = "L51599" Then
refnr.Text = testValue
Else
'do nothing
End If
Loop
Close #1
Any tips?
Thanks
There are 5 different ways to that here : http://www.thespreadsheetguru.com/blog/2014/7/7/5-different-ways-to-find-the-last-row-or-last-column-using-vba.
Be aware of the fact that CSV files are not excel files and they cannot contain custom VBA functions (Macros). You will have to create your "findLastRow" function in a global template and assign it to a custom button on one of the toolbars/ribbons. this is explained here : https://msdn.microsoft.com/en-us/library/office/ee767705(v=office.14).aspx.
good luck!

Copying lines from Wordpad into Excel using VBA

I am writing some code where I import some files under TMX (a form of xml).
I tried various options
a) using the Open FileName For input, but this messes up the character encoding
b) opening the file and copying the data using the msoDialog, but this return an error if the file is too large (which is often the case) and this put the data in an utterly messy manner.
c) opening the file using notepad, but there are the same limitations in so far as copying the entirety of the file into Excel as the previous option.
I am not trying to use a shell function calling onto Wordpad.
My issue right now, is that I need to copy the file line by line to treat its content according to my needs (hopefully without losing the character encoding
Would someone know how to copy every single line from the file opened in WordPad and paste it post treatment (selection of the relevant elements) into Excel?
Thank you
For large files you can use this solution:
Public Sub ImportTMXtoExcel()
Call Application.FileDialog(msoFileDialogOpen).Filters.Clear
Call Application.FileDialog(msoFileDialogOpen).Filters.Add("TMX Files", "*.tmx")
Application.FileDialog(msoFileDialogOpen).Title = "Select a file to import..."
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
strFileToImport = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
Exit Sub
End If
intPointer = FreeFile()
Open strFileToImport For Input Access Read Lock Read As #intPointer
intCounter = 0
Do Until EOF(intPointer)
Line Input #intPointer, strLine
intCounter = intCounter + 1
Worksheets(1).Cells(intCounter + 1, 1).Value2 = strLine
Loop
Close intPointer
End Sub
For other encodings you can use ADO's Stream as described in this solution:
VB6/VBScript change file encoding to ansi
If you have large files which require ADO's Stream then you might want to consider breaking down the large files first as described in this solution:
How to split a large text file into smaller files with equal number of lines?
The following website provides a tool which mimics the Unix command split for Windows in command prompt: https://www.fourmilab.ch/splits/

Resources