vbscript reads File object properties, but won't delete the file - vbscript

Here is my (very simple) code:
if fs.FileExists(strPath) then
set thisFile=fs.GetFile(strPath)
wscript.echo thisFile.Name & " (" & thisFile.Size & ") will be deleted"
thisFile.Delete
end if
The path is correct, because I can read the file name and file size in the output. However, this is the output I'm getting:
D:\Inetpub>cscript PDFDelete.vbs
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.
131_1443_cds101711.pdf (28660) will be deleted
D:\Inetpub\PDFDelete.vbs(38, 3) Microsoft VBScript runtime error: File not found
As you can see, I get the proper output on the file properties, so I know I have a valid reference to the file object, but trying to execute the Delete() method on that exact same file object produces a "File not found" error?!
It makes no sense to me. How can the file be "not found" if I just accessed its name and size properties?
EDIT I should have mentioned, I initially was using the code "fs.DeleteFile(strPath)" when I first got the "File Not Found" error. I changed it to the more direct "File.Delete()" method, but the error persists.

You can try:
if fs.FileExists(strPath) then
set thisFile=fs.GetFile(strPath)
wscript.echo thisFile.Name & " (" & thisFile.Size & ") will be deleted"
fs.DeleteFile strPath
end if
http://www.devguru.com/technologies/vbscript/14055

I found the issue.
There was a stray line of code further down in the script that was referencing thisFile.Size, after trying to delete that file. The error was happening on that line, not on the thisFile.Delete line.
Moral of the story: make use of the On Error Resume Next/On Error Goto 0 error trapping from the start, and things get a lot clearer.

Related

VBScript Invalid Character 800A0408 error

After much searching, I have not been able to find a solution to the error. This script is used to find corrupt cache files in the c:\Windows\Installer directory
this is the offending line of code:
Log "Debug: Found " & dicSUpdatesAll.Count – iCnt & " unique patch(es) in folder " & Folder
the full script can be found here gist

Code Error 800A0409 - Unterminated String Constant (Japanese Windows)

This one is kind of strange to me. Prior to posting I did research this error code and according to many articles out there it seems relatively a straight forward issue. The issue is generally related to either missing double quotes in a string or where a string spans across multiple lines.
However, in my case neither of the above seem to be the cause of the issue. The strange thing is my code works fine in English windows operating system but I encounter this error only in the Japanese version of windows.
The error is pointing to the following line of code:
WScript.Echo "PFXファイル " & pfxFileName & " は存在しません。"
Any ideas why this would only happen in the Japanese version of Windows?
Here is the block of surrounding code in case it gives any further clues:
' check if pfx file exists
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
pfxFileExists = 0
Do
If fso.FileExists(pfxFilePath & pfxFileName) Then
' it exists, continue
pfxFileExists = 1
Else
' The PFX file does not exist.
WScript.Echo "PFXファイル " & pfxFileName & " は存在しません。"
End If
Loop Until pfxFileExists = 1

How do I properly configure conditional actions with user input in VBS with MsgBox?

I have been trying to get a VBS script to work for a while now with msgbox. When I use a single msgbox statement, it works. As soon as I start adding conditional input options, then it doesn't work.
I posted this question on Super User and I was told to use the "dim" statement, and to post on this website, and I have done both now. Here is some of the code I am trying that works. (Please ignore my example.)
Option Explicit
Dim vbsmsg, vbsyes, vbsno
vbsmsg=MsgBox("Proceeding will wipe the contents of your C: Drive. Proceed?", 1+48, "Format Drive C:")
When I run the above code via a shortcut I get a dialog like this:
But if I add the following, I get a run-time error when clicking "OK" or "Cancel"
If vbsmsg=1 Then
vbsyes=MsgBox("The contents of your C: Drive could not be successfully deleted.", 0+64, "Error Formatting Drive C: - System Error 5")
If vbsmsg=2 Then
vbsno=MsgBox("Not all of the contents of your C: Drive were successfully deleted. Please try again.", 0+64, "Error Formatting Drive C: - System Error 303")
The line/character in the error is between the "0" and "3" in "System Error 303"
I have tried a great deal of troubleshooting already. I have tried altering the dim statement, adding option explicit, using 1 and 2 instead of 6 and 8, etc... nothing seems to work. When I commented out the 2nd part, instead of getting an error after executing the file, it just closed on me. I am positive all of my syntax is correct and in the right format. I changed 1 and 2 to vbOK and vbCancel and when I changed it back it wouldn't work at all and gave me the error pictured on this page right away.
If anyone knows what is wrong with my examples, I would greatly appreciate it. I am fairly new to working with VBS files, but I have been working with .bat files for a long time and none of those principles seem to be working here,
I would appreciate any assistance, even if it is small,
Give this example a try:
Option Explicit
Dim Title,Question
Title = "user input in VBS with MsgBox"
Question = MsgBox("Proceeding will wipe the contents of your C: Drive. Proceed ?",vbYesNo+vbQuestion, Title)
If Question = vbYes Then
MsgBox "We proceed wipping your C:\ drive",vbExclamation,Title
'Call your sub here to continue proceeding your script
Else
MsgBox "Canceling the operation !",vbCritical,Title
Wscript.Quit()
End If
For more information about MsgBox Constants
While #Hackoo's answer is technically correct it doesn't answer the initial question, so I'll attempt to here.
The reason for the error
Microsoft VBScript compilation error: Expected 'End'
is due to the If statement spanning more then one line without an End If to finish the statement block, as in #Hackoo's example adding End If will correct this error.
If for whatever reason you wanted to keep the syntax condensed you weren't far away you had two options;
Put the If statements all on one line
Option Explicit
Dim vbsmsg
vbsmsg = MsgBox("Proceeding will wipe the contents of your C: Drive. Proceed?", vbYesNo + vbQuestion, "Format Drive C:")
If vbsmsg = vbYes Then Call MsgBox("The contents of your C: Drive could not be successfully deleted.", vbExclamation, "Error Formatting Drive C: - System Error 5")
If vbsmsg = vbNo Then Call MsgBox("Not all of the contents of your C: Drive were successfully deleted. Please try again.", vbCritical, "Error Formatting Drive C: - System Error 303")
which can be a little ugly looking at sometimes hard to follow (but that's just my opinion).
Use the Line Continuation Character (_) to allow a single statement to span multiple lines, in VBScript this is also known as a Statement Break.
Option Explicit
Dim vbsmsg
vbsmsg = MsgBox("Proceeding will wipe the contents of your C: Drive. Proceed?", vbYesNo + vbQuestion, "Format Drive C:")
If vbsmsg = vbYes Then _
Call MsgBox("The contents of your C: Drive could not be successfully deleted.", vbExclamation, "Error Formatting Drive C: - System Error 5")
If vbsmsg = vbNo Then _
Call MsgBox("Not all of the contents of your C: Drive were successfully deleted. Please try again.", vbCritical, "Error Formatting Drive C: - System Error 303")
As already mentioned it goes without saying that you should endeavour to use the VBScript Named Constants in code wherever possible instead of hard coded numeric values.

Getting error 800a03ec while opening an Excel file

I have written following code to convert XLSX file to CSV format:
If WScript.Arguments.Count < 2 Then
WScript.Echo "Error! Please specify the source path and the destination. Usage: XlsToCsv SourcePath.xls Destination.csv"
Wscript.Quit
End If
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
oBook.SaveAs WScript.Arguments.Item(1), 6
oBook.Close False
oExcel.Quit
It was working fine when I was giving server path for XLSX file. But, when I am giving local machine path, it is giving me following error:
File could not be found. Check the spelling of the file name, and verify that file location is correct. If you are trying to open the file from list of most recently used files, make sure that file has not been renamed, moved or deleted
code: 800A03EC
Source: Microsoft Office Excel
In case anyone with a similar problem finds this, the error code seems to be a general Excel error which means that it could not open the file.
In my case I tried opening the same file manually and found that Excel wanted to repair a corrupted file. I had been allowed to save it with incorrect validations, but it wouldn't open programmatically. Opening it by hand meant that it could show me a dialog asking whether I wanted to fix it or not.
If you are still getting this error, I would do a simple echo on both your arguments to make sure they are doing exactly what they should be doing
wscript.echo "Arg(0): " & WScript.Arguments.Item(0) & " Arg(1): " & WScript.Arguments.Item(1)
Also if you are using cscript.exe to run it, it will by default be looking for the files in c:\windows\system32\ directory
In my case the corresponding message is "Unable to set the PaperSize property of the PageSetup class". That occurs when the standard printer is not capable of the page format of the Excel workbook/sheet.

Is file path needed in (Shell Function) VBA?

I have a Matlab-generated executable file, Myfile.exe to call from excel-vba. I learned (Shell Function) is what I need to use.
I don't want to include the whole file path as I do not want to restrict the user to a certain folder in a certain location on each computer.
I have the following code to call the executable, which works fine:
Sub MyExe()
On Error Resume Next
Shell ("C:\Users\elwany\Desktop\Myfolder\Myfile.exe")
If Err <> 0 Then
MsgBox "Can't start the application.", vbCritical, "Error"
End If
End Sub
My problem/question is
I put the executable + the Excel file with the VBA project in the same folder (Myfolder), and then I modify the code to:
Sub MyExe()
On Error Resume Next
Shell ("Myfile.exe")
If Err <> 0 Then
MsgBox "Can't start the application.", vbCritical, "Error"
End If
End Sub
Sometimes it works, sometimes it doesn't!
For example, yesterday I ran the VBA code, it worked. Today I opened the same Excel file, same folder, same everything, it gives "Can't Start Application" error msg!!
Is it not okay to remove the file path even if I have everything in one folder?
Why does it sometimes work, sometimes not?
Is adding the file path absolutely mandatory?
As you have enquire further about different directories note that you can either
Use ChDir as per my earlier comment to your question
Use Dir instead to validate that myfile.exe is where it needs to be. This method doesn't need error handling to handle the file being missing.
Sub TestB()
Dim strPath As String
strPath = Dir("c:\temp\myfile.exe")
If Len(strPath) > 0 Then
Shell strPath
Else
MsgBox "Path doesn't exist"
End If
End Sub
Sub TestA()
On Error Resume Next
'use the host workbook path
' ChDir ThisWorkbook.Path
'set path here
ChDir "C:\temp"
Shell ("Myfile.exe")
If Err <> 0 Then
MsgBox "Can't start the application.", vbCritical, "Error"
Else
MsgBox "sucess!", vbOKOnly
End If
End Sub
When you run a shell like this without a path specified it runs from the Active Directory. What the Active Directory is depends on the OS, not Excel/VBA (unless you explicitly set it)
Try this instead
Sub MyExe()
On Error Resume Next
Shell (ThisWorkbook.Path & "\Myfile.exe")
If Err <> 0 Then
MsgBox "Can't start the application.", vbCritical, "Error"
End If
End Sub

Resources