finding the last (duplicate) string in .txt file with vb - vbscript

(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

Related

Excel VBA script not running on Excel 2016 with FileSystemObject

I've never used VB(A) before, so forgive me if this is a trivial question.
I am trying to run the code outlined here on Excel 2016 on a Mac.
Sub simpleXlsMerger()
Dim bookList As Workbook
Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object
Application.ScreenUpdating = False
Set mergeObj = CreateObject("Scripting.FileSystemObject")
'change folder path of excel files here
Set dirObj = mergeObj.Getfolder("/...filepath")
Set filesObj = dirObj.Files
For Each everyObj In filesObj
Set bookList = Workbooks.Open(everyObj)
'change "A2" with cell reference of start point for every files here
'for example "B3:IV" to merge all files start from columns B and rows 3
'If you're files using more than IV column, change it to the latest column
'Also change "A" column on "A65536" to the same column as start point
Range("A2:IV" & Range("A65536").End(xlUp).Row).Copy
ThisWorkbook.Worksheets(1).Activate
'Do not change the following column. It's not the same column as above
Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial
Application.CutCopyMode = False
bookList.Close
Next
End Sub
However, I get the error, that goes off without specifying a line:
Any thoughts on how I can modify this code for Mac?
Try this, based on the other (unaccepted) answer to similar question.
Is there an alternative to Scripting.FileSystemObject in Excel 2011 VBA for the mac?
The problem is that Scripting.Runtime library is not available on Mac OS, so you can't do CreateObject("Scripting.FileSystemObject"). This uses the VBA Dir function to build a Collection of files.
Also revised for more efficient "copy" that doesn't use the Copy method.
(untested, so bear with me in case of typos/etc.)
Sub simpleXlsMerger()
Dim bookList As Workbook, vals as Variant
Dim filesObj As Object, everyObj As Object
Application.ScreenUpdating = False
Set mergeObj = CreateObject("Scripting.FileSystemObject")
'change folder path of excel files here
Set filesObj = GetFileList("/...filepath")
For Each everyObj In filesObj
Set bookList = Workbooks.Open(everyObj)
'change "A2" with cell reference of start point for every files here
'for example "B3:IV" to merge all files start from columns B and rows 3
'If you're files using more than IV column, change it to the latest column
'Also change "A" column on "A65536" to the same column as start point
vals = Range("A2:IV" & Range("A" & Rows.Count).End(xlUp).Row).Value2
With ThisWorkbook.Worksheets(1)
'Do not change the following column. It's not the same column as above
.Range("A" & .Rows.Count).End(xlUp).Offset(1, 0).Resize(UBound(vals, 1), UBound(vals, 2)).Value = vals
End With
bookList.Close
Next
End Sub
Function GetFileList(folderPath As String) As Collection
'mac vba does not support wildcards in DIR function
Dim file As String
Dim returnCollection As New Collection
If Right$(folderPath, 1) <> "\" Then
folderPath = folderPath & "\"
End If
file = Dir$(folderPath) 'setup initial file
Do While Len(file)
returnCollection.Add folderPath & file
file = Dir$
Loop
Set GetFileList = returnCollection
End Function
In the VBA window, click tools then add reference. Make sure Microsoft Office Object Library (14 or 16) is checked. You will need this for the automation.
An alternative idea would be to create a loop and save each excel file as a csv then run a batch script.
Example:
copy *.csv merged.csv
For the CSV loop use:
Converting XLS/XLSX files in a folder to CSV

VB Text to Array

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)

Unable to save to a text file using Vbscript

I am trying to save some text to a text file in vbscript but it doesnt work, nor does it show any errors. Here's the code:
sub SaveToFile()
dim fso, fl
Set fso = CreateObject("Scripting.FileSystemObject")
Set fl = fso.OpenTextFile "C:\myFile.txt", 2, True
fl.Write("blahblah")
fl.Close : Set fl = Nothing
Set fso = Nothing
end sub
I was having hard time to post the html code, so here is the link to the code:here
In my eyes you want to append some content to an existing textfile. According here you have to tell the runtime enviroment that you want append something. If so, you have to use the constant value 8 instead of 2.
Assuming that you posted the entire code in your script: you define a procedure there, but you don't call it anywhere. Add a line SaveToFile to your script to actually call the procedure. Also, the parameter list for OpenTextFile must be in parentheses when the returned object is assigned to a variable. The written text OTOH should not be between parantheses (although it doesn't hurt in this particular situation).
Sub SaveToFile()
Dim fso, fl
Set fso = CreateObject("Scripting.FileSystemObject")
Set fl = fso.OpenTextFile("C:\myFile.txt", 2, True)
fl.Write "blahblah"
fl.Close
Set fl = Nothing
Set fso = Nothing
end sub
SaveToFile

Saving a new file with one alphabet preceeding

Please find the code:
Problem is the folder has a large no. of files
=====================================================================================
Dim fso, objFolder, obFileList, folderpath,counter
folderpath = "G:\Everyone\Model Office Testing Documents\HP QC\QTP\PSISAutomation\Logs"
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFolder = fso.GetFolder(folderpath)
Set objFileList = objFolder.Files
For Each File In objFileList
msgbox("5")
If InStr(1,File.Name,"DE_For_Pol_Print_APPA_7A_Copy_") = 1 Then
counter=counter+1
End If
Next
counter=counter+1
msgbox("new file will be saved as: " &"DE_For_Pol_Print_APPA_7A_Copy_"& Chr(64 + Counter))
Do not use the FSO, but make use of the WMI where you put the filename in the SELECT statement, like: "DE_For_Pol_Print_APPA_7A_Copy_%". This should return a collection with only files with the requested filename (faster than a total collection).
There is no count property for file collections, but you can use:
For Each file in fileCollection
counter = counter + 1
Next
This will not access the internal file object and should run reasonably fast.
A second and even faster (but uglier imo) technique is to use the command prompt from a windowshell object and return the dir to the output. The output is just a string. Now, count the amount of matches on your desired string (DE_For_Pol_Print_APPA_7A_Copy_) and that is your counter.
The exact code is left blank as an excercise for the poster.

VB script + change word in VB script on text file

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.

Resources