Handling errors in VBScript during execution - error-handling

Looking for a little help with working on error handling in VBscript.
What I am trying to do is tell the script that if an error occurs during one of the commands that it should re run the script. Basically I am just zipping some files and copying them over to a shared drive, then deleting the original copies once the copy is complete. Now if an error occurs in the zip or copy process I don't want the rest of the script running and having it delete the files. So I just need the script to start over.
At the moment all I have it doing is printing out an echo that says "An error has occurred re-run script" but this is going to be done as a scheduled task so I really need it to be automated. I am just not sure how the syntax would work for this or if it is even possible.
I have seen "On Error Resume Next" but not sure how that plays into how I should be writing this. I don't think I Should be using it because I do not want the script to continue if an error occurs I just want it to start from the beginning again.
This is what it looks like at the moment:
Command2 = "Robocopy.exe " & sLocalDestinationPath & " " & sFinalDestinationPath
RetVal = Shell.Run(Command2,0,true)
If err.Number <> 0 Then
'WScript.Echo "An error has occured copying the files, re-run Script."
End If
If I am going at this problem the wrong way and there is something more efficient I should be doing I would appreciate the help greatly. I am new to VBscript and I am still getting used to it.

May I suggest Eric Lippert's Blog...
Error Handling in VBScript, Part One
Error Handling in VBScript, Part Two
Error Handling in VBScript, Part Three
These resources recently helped me solve a nasty error handling problem.

Related

Malicious macro warning on code that is doing exactly what I want it to

I am building an energy system model that is using a combination of VBA and Python (Pyomo). I am using a small piece of VBA code to call a command line, which in turn uses Pyomo. This code is looping to execute a separate Pyomo optimisation for each day.
The code is working perfectly, apart from the message in the image below being triggered. When I step through the code slowly, the message seems to be triggered by the following line of code which is calling a command line:
Call Shell("cmd.exe /S /c" & "pyomo solve --solver=glpk " & Pyomo_file & " " & DAT_file & " --save-results " & Results_file, vbHide)
I have also tried to run this with the string being simplified down into a single string variable, which I called "Command", but the message below was still triggered.
The hyperlink in the message box (https://support.microsoft.com/en-us/office/malicious-macros-were-found-9e461c61-69d1-4ea9-a386-9ad0deaccfdd?ns=excel&version=90&syslcid=1033&uilcid=1033&appver=zxl900&helpid=56779&ui=en-us&rs=en-us&ad=us) suggests that this issue is triggered by AMSI and that my computer thinks this code is malicious. It is not - it is doing exactly what I want it to!! Digging further I think (but may be wrong) that the virus checks are being triggered by the fact that this string is a combination of so many inputs - the virus checker thinks this is obfuscation.
A few further points:
This line of code is within the daily loop I mentioned above. The
error does not get triggered until the loop has already happily
executed this line >30 times.
Bizarrely it seems to get thrown out on
the same date each time I try to run the loop. If I skip that date, it falls over again at a later date...
I have set my macro security settings to "enable all macros" and this
still happens. I only have the one Office 365 licence in my
organisation (my own company) so I don't think there can be any odd admin
permissions causing this problem.
Finally, I have tried to define the folders I am using as 'safe locations' and this doesn't help either.
Ideally, I would like to just disable the AMSI software while this command line is being executed. But I don't know how to do this of whether it is even possible. If not, any alternative ideas?!
I tried to run the MpCmdRun.exe script suggested by MS in this post, and it seems to have worked. It's possible that is just fluke, but it is working for now! Fingers crossed!

VB.net app will only run as Administrator only

I made a few improvements to code that has been functioning without issues. On the development, the app runs with a problem. Installed on a test computer and it does not run unless I right click and run as administrator. The below code is where gets not running as Administrator.
The for loop is adding file names to a list. Administrator the program just ends no errors just quits. i counter gets to 3 of a total of 6 files. Never gets through to post the message "Did it make it here". But does post the message inside the for loop. i counts to 3. If run as admin then no issues. All file names are short and basic with no special characters. The files locations is Application.CommonAppDataPath. The loop is called from Form load.
Hoping someone could tell me what is going on.
Try
Selected_Machine = XMLReadSetting("Machine", "Selected", "Selexx")
For i = 0 To UBound(files)
MessageBox.Show("Here 2 i " & i & " File Name" & files(i))
cboMachine.Items.Add(IO.Path.GetFileNameWithoutExtension(files(i)))
If Selected_Machine = IO.Path.GetFileNameWithoutExtension(files(i)) Then
cboMachine.SelectedItem = IO.Path.GetFileNameWithoutExtension(files(i))
End If
Next
Catch err As SyntaxErrorException
MessageBox.Show(err.Message)
End Try
MessageBox.Show("Did it make it here?")
Found the issue. Inside the for loop it make a change that calls the text changed event of the list box. In the text changed event I write data to a settings file. The settings file did not have write access. Not sure how that happend but problem solved
Thank you all for the help.

Problem handling errors with FileSystemWatcher

To start with it has been many years since I have done much programming, probably about 15 years, in fact VB 6 was still being taught then so I'm not up to date on anything and can get lost in what I'm reading but I am trying. I'm using Visual Studio 2019 and trying to create a VB Windows Forms App that uses the FileSystemWatcher. Unfortunately the only solutions to my problem that I could find are in C#. I tried to transfer them to my app but couldn't get them to work. Actually Visual Studio wasn't happy with what I put in and wouldn't run at all, probably due to incorrect syntax.
This part of my little app is supposed to copy a file that another program creates, while the other program is running, and place the copy in another folder. It seemed simple, detect that the file had been changed and then copy the changed file. Well I came across a few problems.
The first problem is that if I create an empty file the code works most times with no problems but occassionally 2 copies of the file are created. I could live with that but.
If I replace the empty file with a larger file, the file that it is meant to copy, then it can make 3 or 4 copies and most times produces a messagebox telling me that it can't access the file because it is in use. The main program is also minimised to display the error message, which I don't want.
Even if my app is the only program running and I replace the watched file manually with the larger file I still get the file in use error, so I am assuming that the event has been triggered twice and one of them is the process that is using the file and causing the error.
If I tell the error message to cancel then my program continues and produces only 1 copy of the file. Which is what I do want.
The second problem is that the file being copied is also accessed by another program for a short period imediately after it has been changed and this also causes an extra few copies of it to be made and sometimes a file in use error message box appears, and again the main program is minimised to display the error message. I originally had other IO.NotifyFilters in place that weren't really necassary and thought that they may have been triggering the errors so I removed them, but it made no difference.
The most common error is that the file is in use but there has also been the odd "Unhandled exception has occured in your application. could not find file.". The only reason that I can think of for this error is that the file may have been renamed to a backup file and a new version created by the main program at the exact time my program tried to access it.
From what I have read the FileSystemWatcher can trigger multiple times and I presume that this is what is causing the duplicate copies from both problems.
I need my app to make only 1 copy without the error messagebox appearing as this program needs to run in the background with no user input. Essentially this part of my app is an external program to backup a file when the file changes because the main program changes this file often but only seems to back up the file every few hours.
The following code is what I have used but nothing that I have tried has caught the error so I removed the error event handler. This code was copied from something else that was similar and in C# then modified for my purpose. I thought that the {} were used for C# not VB but it seems to work and if I take them out it won't.
My code for the FileSystemwatcher is:-
WatchFile = New System.IO.FileSystemWatcher With {
.Path = Path.GetDirectoryName(strArkMapFileNamePath),
.Filter = Path.GetFileName(strArkMapFileNamePath),
.NotifyFilter = IO.NotifyFilters.LastWrite
}
' add the handler to each event
AddHandler WatchFile.Changed, New FileSystemEventHandler(AddressOf OnLastWrite)
'Set this property to true to start watching
WatchFile.EnableRaisingEvents = True
The event handler is:-
Private Sub OnLastWrite(sender As Object, e As FileSystemEventArgs)
'Copy the Save file to a new folder and rename it.
My.Computer.FileSystem.CopyFile(
strArkMapFileNamePath,
strBackupPath & "\" & strArkMapFileName & "_" &
DateTime.Now.ToString("dd.MM.yyyy_hh.mm.ss") & ".ark",
Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
End Sub
I added an error event handler after AddHandler WatchFile.Changed, New FileSystemEventHandler(AddressOf OnLastWrite) but that did nothing.
I tried to add an on error statement before the end sub and that did nothing either, I presume because the Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, caught the error first.
I got frustrated and tried to add a statement before the Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, but it didn't like that and I didn't expect it to work.
So how do I catch the errors before the FileSystemWatcher acts on the error?
I don't know what I am doing wrong so any help would be appreciated.
Also if anybody could offer code for what I need to do can it please be code for a Windows Forms App because I don't seem to have much luck in converting C# or anything else.
Edit
I have replaced the My.Computer.FileSystem.CopyFile with the File.Copy method as suggested and added a few extra bits..
Private Sub OnLastWrite(sender As Object, e As FileSystemEventArgs)
'Verify that source file exists
If File.Exists(strArkMapFileNamePath) Then
'Copy the Save file to a new folder and rename it.
Dim i As Integer
For i = 0 To 3
Try
' Overwrite the destination file if it already exists.
File.Copy(strArkMapFileNamePath, strBackupPath & "\" & strArkMapFileName & "_" & DateTime.Now.ToString("dd.MM.yyyy_hh.mm.ss") & ".ark", True)
i = 3
' Catch exception if the file was already copied.
Catch copyError As IOException
'If copy failed reset counter
i += 1
End Try
Next
End If
End Sub
Although this shouldn't be required because this is done before the FileSystemWatcher is enabled I have added an If statement to check that the files exists before attempting to copy the file.
I'm not entirely happy with the loop but I know under normal conditions that it's not going to be an endless loop.
Is there a way to just catch the specific errors that I would need to deal with or will it be fine the way it is?
I will probably still need to work out how to stop the FileSystemWatcher from sending more than 1 event or somehow make multiple events appear as 1.
The If statement was the last thing that I added and for some reason the program now seems to only make 1 copy and appears to be faster.
The other external program that accesses the file being copied must be slower to react than my program because now it displays a message that it's waiting until my program has finished copying the file.
My program is now performing as it was intended but I believe that it is just a matter of timing rather than the correct code.

Publish an excel worksheet as an HTML file using a command button

So I have tons of data in my workbook that I need to pass on to my users in a way that allows them to interact with the workbook..., but also limits what they can actually do. So I have made it so they can access certain pages to Add needed data, then I've given access to a menu page so they can run a report.
This report I have found is best if it's an html page.
To that end, I have tried several different ways, save as...and publish. I like the publish version, but I can not for the life of me get this working. All the samples I see, appear to be the same. Here is the line of code in question:
ActiveWorkbook.PublishObjects.Add(xlSourceSheet, ActiveWorkbook.Path & ".htm, "Sheet1", "", xlHtmlStatic, "", "Report Title").Publish True
Every time I get a run time error '1004':
Method 'Publish' of object 'PublishObject' failed
I have the above line of code in a sub, am I missing something? Do I need to set up the publish differently? Thanks for any ideas.
I have had a similar mysterious problem that sometimes it (.Publish) works and sometimes it doesn't, when I try publish.
However, I think the problem might be, in cases when it doesn't work right off the bat, to first save the relevant region as a webpage so that it exists already on the server. After that region has been saved at least once (manually or else maybe with .SaveAs .. see below), then the publish might work.
Here is an example of how I get this to work more consistently, something to convey the structure that works for me:
wkb=ActiveWorkbook.Name 'save wb for later access
url="http://a.com/b.htm" 'save to Internet
sheetname="c"
Sheets(sheetname).Range("d1:e2").Select 'activating sheet may be necessary
On Error Resume Next 'anticipate error to handle it
'Now comes the publish line the first time... which may work.. or not
ActiveWorkbook.PublishObjects.Add(xlSourceRange,url,sheetname,"d1:e2",xlHtmlStatic,"blah","moreblah").Publish (True) 'may fail to create page on website if page didn't already exist
theerr=Err.Number
On Error GoTo 0 'back to default error handling (none)
If theerr <> 0 Then 'if here perhaps because page nonexistent
'msgbox "maybe add warning here [FYI]"
Sheets("dummysheetwithlittleornodata").Copy 'will create workbook
On Error Resume Next
ActiveWorkbook.SaveAs url 'may fail to create webpage first time
ActiveWorkbook.saveAs url 'twice needed for some reason sometimes. [works for me]
On Error GoTo 0
'with fresh dummy html page created, now publish should hopefully work.. let's try again
ActiveWorkbook.Close savechanges:=False 'clean up and avoid popup
Workbooks(wkb).Activate 'get back to correct wkb
Sheets(sheetname).Range("d1:e2").Select
ActiveWorkbook.PublishObjects.Add(xlSourceRange,url,sheetname,"d1:e2",xlHtmlStatic,"blah","moreblah").Publish (True) 'hopefully if failed first time, now it succeeded ! good luck.
End If
The above code structure has allowed me to solve several publish problems I was having. All the techniques together have been enough so far to allow me to save a range from a sheet as a webpage (to server I have write access to) without having to do anything manually (like a manual save or even click on popup). Good Luck.
[The different non-obvious techniques include activating a range before trying a range publish, using the error handling approach and anticipating failure at certain points, the 2x saveas to compensate for mysterious inconsistent failures when using one saveas only, closing and getting back to original workbook cleanly, and using saveas to "guarantee" page exists in form that will make publish to succeed more consistently.]

VB6 How to catch an ADO Command Timeout error and display custom MsgBox

I have looked through all of the VB6 Error Numbers to no avail, and it seems the command object itself takes care of the error messagebox in the background. What I need to know is if their is someway to change the MsgBox for the ADODB.CommandTimeout error itself. My first thoughts were to just catch the error (using error numbers) and then set a MsgBox that way. However, I can't find any documentation on any error numbers handling ADO Events. Any suggestions?
For whatever it's worth, the error code is 0x80040e31. You can Google for "error 80040e31 timeout expired". And, of course, you can check for that error status in your code.
Here is a list of ADO error codes:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms677004%28v=vs.85%29.aspx
Alright, I got smart and used this:
On Error GoTo ERRS
....
ERRS:
MsgBox Err.Number
This gave me the specific error number to catch (in this case: "-2147217871") and from there use a simple If statement to test if the error number = -2147217871 and if it does, display my MsgBox. Works like a charm (well, as much "charm" as VB6 and ADO has, I guess). I am still getting used to the legacy error handling of VB6. Thanks paulsm4 or your assistance!