copy a file and get location of file at same time VBS - file

I can copy, but I don't know what to put for getting the current directory so it doesn't matter where the file is but it copies it. The code would be something like this:
Set fso = CreateObject("Scripting.FileSystemObject")
strFolder = fso.GetParentFolderName(WScript.ScriptFullName)
Const DestinationFile = "C:\Users\John\Foldar\output.vbs"
Const SourceFile = "fso.BuildPath (strFolder, "getty.vbs")"
If fso.FileExists(DestinationFile) Then
If Not fso.GetFile(DestinationFile).Attributes And 1 Then
fso.CopyFile SourceFile, "C:\Users\John\AnyFile\", True
Else
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
fso.CopyFile SourceFile, "C:\Users\John\AnyFile\", True
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
End If
Else
fso.CopyFile SourceFile, "C:\Users\John\AnyFile\", True
End If
Set fso = Nothing
What I need is like:
Const SourceFile = "currentplace\something.vbs"
Or something like that. Because I get the error Expected end of statement at line 4 char 48.
Here is my updated code:
Set fso = CreateObject("Scripting.FileSystemObject")
strFolder = fso.GetFolder(".").Path
DestinationFile = "C:\Test\getty.vbs"
SourceFile = fso.BuildPath(dir, getty.vbs)
If fso.FileExists(DestinationFile) Then
If Not fso.GetFile(DestinationFile).Attributes And 1 Then
fso.CopyFile SourceFile, "C:\Test\", True
Else
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
fso.CopyFile SourceFile, "C:\Test\", True
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
End If
Else
fso.CopyFile SourceFile, "C:\Test\", True
End If
Set fso = Nothing

GetParentFolderName(WScript.ScriptFullName) returns the name of the folder that contains the script interpreter. That may or may not be the current working directory. If you need the working directory, do not use this method.
There are several ways to determine the actual working directory. One method was already proposed by #Jay:
strFolder = fso.GetFolder(".").Path
Others would be
strFolder = fso.GetAbsolutePathName(".")
or the CurrentDirectory method of th WshShell object
strFolder = CreateObject("WScript.Shell").CurrentDirectory
Edit: As for the error you get, Const only works with literals, i.e. you cannot do something like
Const foo = fso.BuildPath(dir, filename)
or even something like
Const foo = 23 + 42
No calculations, no function/method calls, no string concatenation, nothing. Only literal constants:
Const foo = "something"
Const bar = 23
If you want to assign the result of a method call, you must use a variable:
foo = fso.BuildPath(dir, filename)

Related

How to compare array to array using VBScript?

I would like to check a data in my file exist or not in an array data that I have. It will return 1 and 0 if its exit or not. Inside my file is like this:
2j2H4F6d9d0d3hdfasgt.y7
But I cut the last 2 lines. And my array data is like this: [2w fr 5k 2j 0w]. I want to check whether my array data exist inside my file.
Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20
XX = 0
Set wshShell = CreateObject("WScript.Shell")
strFBString = wshShell.ExpandEnvironmentStrings("%FB%")
WScript.Echo "==>"
WScript.Echo "strFBString: " & strFBString
Set wshShell = Nothing
For i = 1 To Len(strFBString) Step 2
If StrComp(Mid(strFBString, i, 2), [2w fr 5k 2j 0w]) = 0 Then
XX = 1
End If
Next
WScript.Echo "XX: " & XX
WScript.Quit(XX)
For one thing, [2w fr 5k 2j 0w] is not a valid array definition in VBScript. If you want to define an array with these 5 string elements you need to do it like this:
Array("2w", "fr", "5k", "2j", "0w")
Also, StrComp() is for comparing a string to another string. It does not support comparing a string to an array. For comparing a string to each element of an array you need a loop. How to build that loop depends on the result you want to achieve, though.
Looking at your code it seems you want to find a match in 2j2H4..., but not in w2j2H..., so simply using InStr() probably won't work for you. In that case you could use an inner loop for the comparison:
ref = Array("2w", "fr", "5k", "2j", "0w")
For i = 1 To Len(strFBString) Step 2
For Each s In ref
If Mid(strFBString, i, 2) = s Then
'...
End If
Next
Next
But like I already said, details depend on the desired end result. If you want to check if your input string contains any of the array values you could do something like this:
ref = Array("2w", "fr", "5k", "2j", "0w")
found = False
For i = 1 To Len(strFBString) Step 2
For Each s In ref
If Mid(strFBString, i, 2) = s Then
found = True
Exit For
End If
Next
Next
If on the other hand you wanted to check if your input string contains all of the reference strings you'd probably do something like this instead:
ref = Array("2w", "fr", "5k", "2j", "0w")
For Each s In ref
found = False
For i = 1 To Len(strFBString) Step 2
If Mid(strFBString, i, 2) = s Then
found = True
Exit For
End If
Next
If Not found Then Exit For
Next
You could also use an entirely different approach, like putting your data in a dictionary:
data = CreateObject("Scripting.Dictionary")
For i = 1 To Len(strFBString) Step 2
data(Mid(strFBString, i, 2)) = True
Next
Using that approach you could check if the data contains any of the reference values like this:
found = False
For s In Array("2w", "fr", "5k", "2j", "0w")
If data.Exists(s) Then
found = True
Exit For
End If
Next
or check if the data contains all of the reference values like this:
found = True
For s In Array("2w", "fr", "5k", "2j", "0w")
If Not data.Exists(s) Then
found = False
Exit For
End If
Next

close console after VBS script executes

I have a multi screen computers system. Once in a while, for a reason I don't understand, the dialog boxes are on the wrong monitor. For instance, I'll have a program running in monitor A and an OK box will open in monitor D. This is very frustrating.
I found a VBS script called "PositionDialogs.vbs" found here: https://www.realtimesoft.com/ultramon/scripts/
Const SNAP_TO_MONITOR = False 'set this to True to ensure dialogs aren't placed between two monitors
Const INTERVAL = 2 'number of seconds the script waits before enumerating open windows again
Set sys = CreateObject("UltraMon.System")
Set wnd = CreateObject("UltraMon.Window")
Set wndParent = CreateObject("UltraMon.Window")
'create the two maps used to store positioned windows
Set arrAdd = CreateObject("Scripting.Dictionary")
Set arrLookup = CreateObject("Scripting.Dictionary")
Do While True
'enumerate all application windows
For Each w In wnd.GetAppWindows(True)
If w.HWndParent <> 0 Then
wndParent.HWnd = w.HWndParent
move = True
If arrLookup.Exists(w.HWnd) = True Then move = False
arrAdd.Add w.HWnd, 0
If move = True Then
If SNAP_TO_MONITOR = False Then
If w.Monitor <> wndParent.Monitor Then
w.Monitor = wndParent.Monitor
w.ApplyChanges 1 + 2 'WNDCHANGE_RESIZE_TO_FIT + WNDCHANGE_CLIP_TO_WORKSPACE
End If
Else
Set parentMon = sys.Monitors(wndParent.Monitor - 1)
parentLeft = parentMon.WorkLeft
parentTop = parentMon.WorkTop
parentRight = parentLeft + parentMon.WorkWidth
parentBottom = parentTop + parentMon.WorkHeight
dlgLeft = w.Left
dlgTop = w.Top
dlgRight = dlgLeft + w.Width
dlgBottom = dlgTop + w.Height
If dlgLeft < parentLeft Then
w.Left = parentLeft
ElseIf dlgRight > parentRight Then
w.Left = parentRight - w.Width
End If
If dlgTop < parentTop Then
w.Top = parentTop
ElseIf dlgBottom > parentBottom Then
w.Top = parentBottom - w.Height
End If
w.ApplyChanges 0
End If
End If
End If
Next
'swap maps, then clear arrAdd. this way we don't have entries for windows which no longer exist
Set temp = arrLookup
Set arrLookup = arrAdd
Set arrAdd = temp
Set temp = Nothing
arrAdd.RemoveAll
WScript.Sleep INTERVAL * 1000
Loop
that will move the dialog box to whatever monitor called it.
I have it running on Windows startup using a batch file, and it runs as a process. My problem is that the console window that shows doesn't go away unless I click the X to close it.
The bath files looks like this:
wscript PositionDialogs.vbs
exit
I assume there is something I can add to the script to make it close after it loads itself into memory? If so, what?
aschipf was correct.
I made the batch file
start PositionDialogs.vbs
exit
(used START instead of WSCRIPT) and it closed as expected, while the process still ran in task manager

Recursively search files for information contained in excel cell and return path

Okedoke... I have an Excel spreadsheet with a filename in column A. The filenames listed in column A appear in one or more text files in one or more source directories.
I need Excel to search the text files recursively and return the path(s) of the file(s) that contain the filename specified in column A into column B. If more than one file go to column C etc.
The Excel sheet would be
__________________________________
__|______A___________|______B_____|
1 | filename.avi | |
2 | another_file.flv | |
The text files to search would be in multiple directories under C:\WebDocs\ and are DokuWiki pages some are quite short, such as this page that would need to be returned
===== Problem Description =====
Reopen a closed bank reconciliation.
===== Solution =====
Demonstration of the tool box routine that allows reposting of the bank rec.
{{videos:bank_rec_reopen1006031511.flv|}}
===== Additional Information -cm =====
You may have noticed that in the video there is a number to the right of the bank account number. In this case it was a 0. That indicates department 0 which is all departments. You get the department 0 if you have all departments combined using the option in the bank set up called "One Bank for All Departments". If this setting is not checked then when you create your starting bank rec for each department you will get a 1 to the right of the bank rec for department 1 and so on. You should normally only have a 0, or have numbers 1 or greater. If you have both, then the method was changed after the initial bank rec was made. You just have to be aware of this as you move forward. As always backup before you make any changes.
There are some other pages though that are quite long that do not contain videos but would be in the directories being searched. Format is the same, plain text, ==== are place holders for headings may contain links to other pages/sites.
I did find an existing VBA script that sort of does what I need it to. It does not recurse and returns too much information, date/time stamp for instance, where all I need is the path.
Private Sub CommandButton1_Click()
Dim sh As Worksheet, rng As Range, lr As Long, fPath As String
Set sh = Sheets(1) 'Change to actual
lstRw = sh.Cells.Find(What:="*", After:=sh.Range("A1"), LookAt:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row
Set rng = sh.Range("A2:A" & lstRw)
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
fPath = .SelectedItems(1)
End With
If Right(fPath, 1) <> "\" Then
fPath = fPath & "\"
End If
fwb = Dir(fPath & "*.*")
x = 2
Do While fwb <> ""
For Each c In rng
If InStr(LCase(fwb), LCase(c.Value)) > 0 Then
Worksheets("Sheet2").Range("C" & x) = fwb
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(fwb)
Worksheets("Sheet2").Range("D" & x) = f.DateLastModified
Worksheets("Sheet2").Range("B" & x) = f.Path
Worksheets("sheet2").Range("A" & x) = c.Value
Columns("A:D").AutoFit
Set fs = Nothing
Set f = Nothing
x = x + 1
End If
Next
fwb = Dir
Loop
Set sh = Nothing
Set rng = Nothing
Sheets(2).Activate
End Sub
My attempts at moification so far have generally resulted in a broken script and have thus led me here asking for help.
Thanks,
Simon
Downlaoded the win32 port of the GNU tool grep from http://gnuwin32.sourceforge.net/
Saved the list of video files into a plain text file instead of using a spreadsheet.
grep --file=C:\file_containing video_file_names.txt -R --include=*.txt C:\Path\To\Files >grep_output.txt
The information written to the grep_output.txt file looked like
C:\wiki_files\wiki\pages/my_bank_rec_page.txt:{{videos:bank_rec_reopen1006031511.flv|}}
So there was the path to the file containing the video name and the video name on one line.
Imported the grep_output.txt file into a new Excel workbook.
Used regular formulae to do the following
Split Column A at the "/" to give the path in Column A and the page and video information in Column B
Split the data in in Column B at the ":{{" characters leaving page name in Column B and video information in Column C
Stripped the :{{ and |}} from the front and rear of the string in Column C
From my limited experience, it seems you'd want to perform 4 tasks.
1) Loop through Directories
2) Loop through files per directory (Good idea to keep the filename in a variable)
3) Test the text file for values. Would suggest clear a "scribble sheet", import the file, run a check. e.g.
Sheets("YourScratchPatch").Select
Application.CutCopyMode = False
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & yourpath & yourfile.txt, Destination:=Range("A1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 2
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
4) if values are found, write the file name variable to the index sheet.
I'm sure there should be better (arrays?) ways to do the comparison check as well, but it depends on what's inside the text file (i.e. just one file name?)
More info on the text file structure would be useful. Hope this helps.

find and replace symbol using vbs

I am working a 1XXX words documents, I want to use vbs to changing the status of checkbox faster but I can't found any work solution, after that, i wonder if find and replace can solve my issue, so i wrote some code for this
Const wdReplaceAll = 2
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Open("C:\checkbox.doc")
Set objDoc = objWord.Documents.Add()
Set objSelection = objWord.Selection
objSelection.Find.Text = "#1"
objSelection.Find.Forward = TRUE
objSelection.Find.MatchWholeWord = TRUE
objSelection.Find.Replacement.Text = objSelection.InsertSymbol 253, "Wingdings"
objSelection.Find.Execute ,,,,,,,,,,wdReplaceAll
But, it can't work, and always show the error on the objSelection.InsertSymbol 253...
You can't use InsertSymbol in an assignment like that. Either replace the search text with an appropriate character formatted as "Wingdings":
With objSelection.Find
.Text = "#1"
.Replacement.Text = ChrW(61693)
.Replacement.Font.Name = "Wingdings"
...
End With
objSelection.Find.Execute ,,,,,,,,,,wdReplaceAll
or just Find the search text and then use InsertSymbol on the selection:
objSelection.Find.Text = "#1"
objSelection.Find.Execute
objSelection.InsertSymbol 253, "Wingdings"

Process output of a sequence of files in Matlab

EDIT 3
Hi! I had problems with the matrix dimensions but I've solved it. Now my problem is that I want to do the same operation on a large series of files on the same folder and I want write the output values on a separate line on text.txt. With the first one it works but it doesn't 'write' to the 'text', the rest. Is there something wrong?
myPath = 'C:\EX\';
a= dir (fullfile(myPath,'*.DIM'));
fileNames = { a.name };
% Rename files
for k = 1:length(fileNames)
newFileName = [fileNames{k}(1:2) fileNames{k}(4:6) '.txt'];
movefile([myPath fileNames{k}], [myPath newFileName]);
end
filePattern=fullfile( myPath,'*.txt');
txtFiles= dir(filePattern);
for k = 1:length(txtFiles)
baseFileName=txtFiles(k).name;
fullFileName= fullfile(myPath,baseFileName);
fid=fopen(fullFileName, 'r');
for i = 1:18
m{i} = fgetl(fid);
end
result2 = m{18};
result2b= result2([12:19]);
fid=fopen(fullFileName, 'r');
for i = 1:30
m{i} = fgetl(fid);
end
result3 = m{30};
result3b= result3([12:19]);
fid=fopen(fullFileName, 'r');
for i = 1:31
m{i} = fgetl(fid);
end
result4 = m{31};
result4b= result4([12:20]);
fid=fopen(fullFileName, 'r');
for i = 1:19
m{i} = fgetl(fid);
end
result5 = m{19};
result5b= result5([12:20]);
text= {baseFileName, result2b, result3b, result4b, result5b};
final= [Fields'; text];
end
Really thanks in advance!
Index exceeds dimensions is exactly what it means.
Try to put a breakpoint at the line where it occurs and check the dimension of result2. Assuming it is a vector, you will find that its length is less than 19.

Resources