Finding txt File path dynamically - vb.net

I need to read a txt file but I don't have the path. The text file is two directories before the path of the script I'm running. I thought I could use "WScript.ScriptFullName" and then just use an instrRev and make it split the str at "/". But It doesn't work Could you guys help me with that. I have to run this on multiple computers so the path changes but the text file will always be two derictories above the script path
My code so far
Dim strScriptPath
strScriptPath = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
WScript.Echo strScriptPath
WScript.Echo(WScript.ScriptFullName)
Dim DashRev
DashRev = instrRev(WScript.ScriptFullName, "/")
wscript.echo DashRev

First replace the "/" with "\"
Then try the following. This seems to work for me:
Dim strScriptPath
strScriptPath = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
WScript.Echo strScriptPath
WScript.Echo(WScript.ScriptFullName)
Dim first, sec
first = instrRev(strScriptPath, "\",Len(strScriptPath)-1)
sec = instrRev(WScript.ScriptFullName, "\",first-1)
wscript.Echo "parent = " & Left(strScriptPath,sec)
The idea being that strScriptPath is always going to end in "\" and first is going to exclude that from the instrrev by using the starting position of one less than the length of the path. Same thing essentially with sec.

Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
WScript.Echo FSO.GetFile(WScript.ScriptFullName).ParentFolder.ParentFolder.ParentFolder.Path

Related

Search for file in folder backwards

So far all the examples for checking if a file is in a directory has been to get a list of files in that directory then compare your items to it. This is a lot of overload for me. I have a list of about 125 files and the directory I want to search in has 8000 files. Can someone instruct me on how to use a file with a list of file names and search a directory for each file.
Moved here from comments:
The code below works, but because it's searching through 8000 files in
a directory the code takes a long time to work. I have a document with
350 lines of file names. Instead of going through each file in the
directory for a match to one of the file names in my document. I'd
like to take my list and search the directory for that file. This way
I'm only looping 350 times instead of 8000
Here is my code.
Dim fileNames As String() = System.IO.Directory.GetFiles(imgLocation)
Dim i As Integer
statusText = "Copying Image Files"
i = 0
' Loop over the filenames retrieved
For Each fileName As String In fileNames
' Check if the files is contained or not in the request list
If GraphicList.Contains(Path.GetFileNameWithoutExtension(fileName)) Then
'Debug.Write("Filename " & fileName & vbCr)
Dim FileNameOnly = Path.GetFileName(fileName)
Dim copyTo As String
copyTo = createImgFldr & "\" & FileNameOnly
System.IO.File.Copy(fileName, copyTo, True)
' Do not write to file inside the loop, just add the fact to the list
' Debug.Write("Copy image " & FileNameOnly & vbCr)
imgFilename = (FileNameOnly) + vbCrLf
ImageCount1 = i
BackgroundWorker1.ReportProgress(100 * i / GraphicList.Count())
foundImgFiles.Add(FileNameOnly)
Else
Debug.Write("Missing " & FileNameOnly & vbCr)
notfoundImgFiles.Add(fileName)
End If
i = i + 1
Next

How would I identify a file to copy based on the date in its name?

I am trying to copy a file from one path to another and rename it. However the source folder contains several files, and the naming convention is the following: 123456_EXyymmdd.txt now the 123456 part is a randomly generated number, so I can only identify the file to copy for a given day by the EXyymmdd part. I have the following code where I tried to put the identifying segment of the string as "**" but it doesn't work, probably due to the date:
Sub SOQuestion()
Dim myDate1 As String
Dim Ipan1 As String
Dim Ipan2 As String
Dim mGlobalDate as string
mGlobalDate=Format(Date, "yyyymmdd")
myDate1 = Format(Date, "yymmdd")
Ipan1 = "157782_EX" & mGlobalDate & ".txt"
Ipan2 = "*_EX*" & myDate1 & ".TXT*"
'source path below
FileCopy "C:\sample\" & Ipan2, "C:\sample2\" & Ipan1
End Sub
It's confused because of the wildcard. It would be like copying a bunch of files to one file, which if you think about it, doesn't make much sense. Instead, use the wildcard and the Dir function to get the exact filename and use that as your source argument.
Dim sFilename as String
sFilename = Dir("C:\sample\" & Ipan2)
Then:
FileCopy "C:\sample\" & sFilename, "C:\sample2\" & Ipan1
MSDN Dir Function

vba - loop through subdirectories to find and insert pic

I am trying to create code that will essentially "crawl" from subfolder to subfolder, and find and insert a designated picture.
I've got this bit of working code, which inserts the pic:
Set picture = ActiveSheet.Pictures.Insert(path & "\" & picname & ".jpg")
picture.Select
If I were to put this in a loop, what methods would I need? Reading up on this, I have found lots of related topics, but all are very specific cases with long-winded, extraneous code, making it very hard for a beginner like me to isolate the parts relevant to getting from folder to folder.
I appreciate your time, and thanks in advance for the help.
Something like:
Sub CrawlFolder(ByVal path as String, ByVal picname as String)
Dim file
Dim fs As New FileSystemObject
Dim subdir As Folder
Dim thisdir As Folder
file = Dir(path)
While (file <> "")
Set picture = ActiveSheet.Pictures.Insert(path & "\" & picname & ".jpg")
picture.Select
file = Dir
Wend
Set thisdir = fs.GetFolder(path)
For Each subdir In thisdir.SubFolders
CrawlFolder(subdir)
End Sub
Not tested, just ideas for you to explore based on what I read here, with Tim's help :)

VBscript output not writing correctly

Hello Scripting Experts,
I have a log file on remote servers..
in remote servers c:\vb\text.log
I have included my remote systems in list.Txt like
server1
server2
below is the sample of log..
application working
[10/23/2012 working
[10/24/2012 nos appdown
error found you need to check this
Below is my Script.
Set Fso = CreateObject("Scripting.FileSystemObject")
Set InFile = fso.OpenTextFile("list.Txt")
Set out = fso.CreateTextFile("error.log")
Const ForReading = 1
Do While Not (InFile.atEndOfStream)
strComputer = InFile.ReadLine
today = Date()
Set fso = CreateObject("Scripting.FileSystemObject")
strFilePath = "\\" & strComputer & "\c$\vb\"
Set InputFile = fso.OpenTextFile(strFilePath & "text.log", 1)
Do While Not (InputFile.AtEndOfStream)
strLine = InputFile.ReadLine
If Left(line, Len(today)+1) = "[" & today Then
' line timestamped with today's date
If InStr(line, "nos") > 0 Then
' line contains "error"
out.WriteLine InStr & vbTab & strComputer
End If
End If
Loop
InputFile.close
Loop
out.Close
InFile.Close
Basically the above script should search from current date line only from the text.log file that is [10/24/2012 nos appdown. Then if found as "Nos" in the current date line.. then it should write to the error.log with computer Name.
In my case the output is not coming , however looks like it is searching for the string "Nos".
Kindly gail break me from this situation....
The bug is that you don't specify the explicit option. Like so,
option explicit
This will force VBScript to complain about nondeclared variables. By doing this, you easily can spot misspelled variable names. Delcare variables with dim statement, like so
dim Fso, out
Run the script again and see that you are using a non-existing and non-initialized variable in comparision:
strLine = InputFile.ReadLine ' Read stuff to strLine
If Left(line, Len(today)+1) = "[" & today Then ' ERROR. line has no value!
There are several issues with your adaptation of my script:
As was already pointed out by vonPryz this is the cause of the problem:
strLine = InputFile.ReadLine
If Left(line, Len(today)+1) = "[" & today Then
When you change a variable name from file to strFile you have to change every occurrence of that variable, not just the line where it's assigned.
out.WriteLine InStr & vbTab & strComputer
This line will also fail, because InStr is a function and you don't call it with the correct number of arguments.
today = Date()
This should not be inside a loop unless you expect the date to change during the script run and need to have the current date in every loop cycle.
Set fso = CreateObject("Scripting.FileSystemObject")
fso is instantiated at the beginning of the script. There's no need to re-instantiate it, especially not in each loop cycle. That's just a waste of resources.
Const ForReading = 1
There's no point in defining a constant when you're never using it.
Do While Not ...
Using Do Until ... would be easier to read and to understand.

Excel macro to read input from files created today only

I have an application that exports daily reports in txt format.
I have a macro that extracts certain lines of data from those reports and puts them in an output xls file. my macro's input directory is curently a separate folder that i manually move today's reports into.
I'd like for my macro to be able to just read from the default report folder and only read files created with today's date.
the naming convention of the report files is as follows:
1101_16_16_AppServiceUser_YYYYMMDDhhmmssXXX.txt
not sure what the last 3 digits on the file name represents, but they're always numbers.
Help?
WOW that was fast! thanks... fist time using stackoverflow.
I guess i should include the code that pulls data and dumps it to excel... here it is:
Sub PullLinesFromEPremisReport()
Dim FileName, PathN, InputLn As String
Dim SearchFor1, SearchFor2, OutpFile As String
Dim StringLen1, StringLen2 As Integer
Dim colFiles As New Collection
Dim bridgekey As String
PathO = "C:\Documents and Settings\GROMERO\Desktop\CM reconciliation\output\"
PathN = "C:\Documents and Settings\GROMERO\Desktop\CM reconciliation\input\"
FileName = Dir(PathN)
While FileName <> ""
colFiles.Add (FileName)
FileName = Dir
Wend
SearchFor1 = "BRIDGE KEY"
StringLen1 = Len(SearchFor1)
OutpFile = "RESULTS.xls"
Open PathO & OutpFile For Output As #2
For Each Item In colFiles
Open PathN & Item For Input As #1
Do Until EOF(1) = True
Line Input #1, InputLn
If (Left(LTrim$(InputLn), StringLen1) = SearchFor1) Then
bridgekey = InputLn
End If
Loop
Close #1
Next Item
Close #2
End Sub
Daniel's answer is correct, but using the FileSystemObject requires a couple of steps:
Make sure you have a reference to "Microsoft Scripting Runtime":
Then, to iterate through the files in the directory:
Sub WorkOnTodaysReports()
'the vars you'll need
Dim fso As New FileSystemObject
Dim fldr As Folder
Dim fls As Files
Dim fl As File
Set fldr = fso.GetFolder("C:\Reports")
Set fls = fldr.Files
For Each fl In fls
'InStr returns the position of the substring, or 0 if not found
' EDIT: you can explicitly use the reliable parts of your file name
' to avoid false positives
If InStr(1, fl.Name, "AppServiceUser_" & Format(Now, "YYYYMMDD")) > 0 Then
'Do your processing
End If
Next fl
End Sub
EDIT: So I think, from the code you posted, you could send PathN to the main Reports folder like you desire, then just modify your While statement like so:
While FileName <> ""
If InStr(1, FileName, "AppServiceUser_" & Format(Now, "YYYYMMDD")) > 0 Then
colFiles.Add (FileName)
End If
FileName = Dir
Wend
Two ways you can do this off the top of my head. Assuming you are using a File via the FileSystemObject.
Do an Instr on the file.Name looking for Format(Date, "YYYYMMDD") within the string.
Or use a far simpler approach loop through the files and within your loop do this:
If File.DateCreate >= Date Then
'Do something
end if
Where File is the actual variable used to for looping through the files.
If fileName like "*AppServiceUser_" & Format(Now, "YYYYMMDD") & _
"#########.txt" Then
'good to go
End If