This seems like the most basic of things. There are lots of examples on google, all of which I have put into my code and have gotten the same result.
I beleive I am missing something specific to the language, and it's really getting irritating.
Given
pathName$ = "..\..\images\" + artID + "\" + artNum + "\"
dirTest$ = "..\..\images\" + artID + "\"
If Dir$(pathName$ , ATTR_DIRECTORY) = "" Then
MsgBox "No Dir"
Else
MsgBox "Dir Found!"
End If
(everthing is dimmed correctly)
I have put msgbox's before pathName$ and right before the DIR call, but it fails when it gets to the test. I know for a fact that the dir doesn't exist in certain scenarios, but I would like to trap the error, not have the script crash on failing to find the dir.
I have tried DIR (path,16) DIR$(path,16) DIR (path$,16) DIR$(path$,16) as well as the ATTR_DIRECTORY key word.
How can I gracefully check the existence of a directory in Lotusscript?
The Dir$ command will generate the run-time error code 76 if the directory does not exist. So you can trap the run-time error by adding On Error 76 Resume Next to your code:
pathName$ = "..\..\images\" + artID + "\" + artNum + "\"
dirTest$ = "..\..\images\" + artID + "\"
On Error 76 Resume Next
If Dir$(pathName$ , ATTR_DIRECTORY) = "" Then
MsgBox "No Dir"
Else
MsgBox "Dir Found!"
End If
Inspiration: http://searchdomino.techtarget.com/tip/Finding-files-and-directories-with-LotusScript
I think the better solution is to test a variant with the Dir$ function result. That's because if the dir path is completely wrong the error 76 gives back a variant containing the error. So it should be managed, like this:
`
On Error 76 GoTo PathNotValid
result = Dir$(dirPath$,16)
If result <>"" then
MessageBox dirPath$ + " found :) "
Else
MessageBox dirPath$ + " NOT found :( "
End if
End:
Exit Sub
PathNotValid:
MessageBox dirPath$ + " IS NOT VALID !!!"
result = ""
Resume Next
`
Related
..................................................................................................................................................................
Late-breaking news...
P.P.S. I just read that FileSystem.FileCopy is better than just FileCopy. That's what I'm going to try. But I really would like to know how to use FileCopy inside a loop, meaning, "How do I close files used in FileCopy?" For the big picture made clear, read on.
..................................................................................................................................................................
(Using Windows 10 Pro, Word 365 Pro)
The online Help for FileCopy Src, Dest says that it ... Copies a file from Src to Dest [but] does not work on a currently open file. Both ... files must be closed [by] the Close statement.
But the online help for Close, from link supplied on that page connects to help for Close for the Open statement, which says that it "Closes the file(s) previously opened with the" Open statement, not the FileCopy statement.
So it is that I'm stumped on what to do with this code, which will copy the first code module in the Document to a backup location, but not the second.
Pic#1: Info about what's supposedly going to be copied
Pic#2: Original error message without On Error
(I have no clue why all these blank lines. They're NOT in my Body.)
Please ignore all the OnError stuff for now.
When the second code module should have been copied, execution halted with error "File not found".
Sub BackupModules()
Dim prj As VBProject
Dim comp As VBComponent
Dim code As CodeModule
Set prj = ThisDocument.VBProject
Dim k As Integer, n As Integer
Dim Destination As String, Prefix As String
Prefix = "junk"
k = 0: n = 0
On Error GoTo x
For Each comp In prj.VBComponents
On Error GoTo x
k = k + 1
If comp.Type = vbext_ct_StdModule Then
n = n + 1
Destination = Prefix & n
MsgBox "Copying Standard module " & n & " of " & k & " components encountered: <" & comp.Name & "> to " _
& Destination & "; # lines: " & comp.CodeModule.CountOfLines
On Error GoTo x
FileCopy comp.Name, Destination
MsgBox "Success"
Close
Else
x: If Err.Number <> 0 Then: _
msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & Err.Description: _
MsgBox msg, , "Error", Err.HelpFile, Err.HelpContext: On Error GoTo 0: Close:
End If
Next
End Sub
Then I began experimenting (a LOT as you can see) with On Error Goto x being placed at various places (one at a time and then all, as shown) and the nasty-looking but syntactically and logically correct line that starts x: If Err... placed inside the Else block.
Pic#3: Error msg after using On Error
(FWIW, I just spotted Normal in the Err.Source part of the error message above. Online help says, "When an unexpected error occurs in your code, the Source property is automatically filled in. For errors in a standard module, Source contains the project name. For errors in a class module, Source contains a name with the project.class form." Indeed, the code is in a Module within the Normal Project.)
Pic#4: Line causing error that On Error did NOT trap
So what's wrong? I've tried everything I can think of. The only help I could find for Close did NOT mention its use with FileCopy. My Close usages caused no error but did Close close both the source and the destination file? Surely not. First use of FileCopy worked, files (probably) not closed, thus second use of FileCopy failed. Docs say using FileCopy on an open file will cause error.
On Error Goto x or to 0 is neither here nor there. That's why I said to ignore them at first.
The question is apparently "How do I close both files mentioned in FileCopy?"
P.S. Per opening blurb, I'm NOT gonna do this.
I suppose I could use Open ... For Input As File#1 and specify the Module's name, if it's readily available to code, and also Open ... For Output As File#2 for the destination, use a For loop to copy the number of lines, if available, and then Close both. But I hope I get a solution to my problem before I try that since SURELY FileCopy should work within a loop (and doesn't because of improper close).
Thanks to #TimWilliams, who tipped me off to Export, my final "Backup all modules" routine is quite simple.
Sub BackupModules()
Dim comp As VBComponent
Dim prj As VBProject: Set prj = ThisDocument.VBProject
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
Dim destPrefix As String: destPrefix = "C:\Users\Dov\Google Drive\Word\Modules\"
Dim destFilePath As String
For Each comp In prj.VBComponents
If comp.Type = vbext_ct_StdModule Then
destFilePath = destPrefix & comp.Name & " " & Year(Now) & " " & Month(Now) & " " & Day(Now)
Debug.Print "Copying Standard module <" & comp.Name & "> to <" & destFilePath & ">"
comp.Export (destFilePath)
Else
Debug.Print "Skipping component # " & k & ", <" & comp.Name & ">, type " & comp.Type
End If
Next
End Sub
I'm trying to diagnose an issue with VBScript FileSystemObject.CopyFile, it's reporting Error 53: File Not Found, but it has successfully copied the file! I've tried variations of the CopyFile command, with full destination name or just folder etc no difference, it always copies the file.
Worse, if I purposefully break it, by changing the source file name, I still get Error 53, which is the exact situation I'm trying to catch and report.
On Error Resume Next
'copy the officeUI xml to the Microsoft Office folder
filePath = profilePath & "\Microsoft\Office\"
if not WshFSO.FolderExists(filePath) then
WshFSO.CreateFolder filePath
end if
WshFSO.CopyFile scriptPath & "\Access.officeUI", filePath, True
'copy the foo client zip to \foo
filePath = profilePath & "\foo\"
if not WshFSO.FolderExists(filePath) then
WshFSO.CreateFolder filePath
end if
WshFSO.CopyFile localZip, filePath, True
if Err.Number <> 0 then
'catch that the copy failed
msg = "Failed to copy Foo, please report this to Help Desk." _
& vbCrLf & vbCrLf & "Citrix Server: " & WshNetwork.ComputerName _
& vbCrLf & "Error: " & err.Number & " - " & err.Description
WshShell.Popup msg, , "Foo Launcher", 16
Err.Clear
WScript.Quit
end if
The error is occuring on the final CopyFile call.
The problem was due to the Error handling logic in VBS, it was reporting the error number from an earlier line! The On Error Resume Next allowed the code to continue to run, but subsequent calls, even successful ones, did not overwrite the Err object. So when I did want to check the result, it picked up this previous error.
So from this I think that unless you want If Err.Number... everywhere is that before each 'block' of code you want to error check, clear the Err object first with Err.Clear.
I wish VBScript had On Error Goto like its cousin!
Run-time error '52': Bad file name or number
I would like to ask for your help and suggestions as to why my code encounters a "run-time error '52': bad file name or number" when I am using a computer which do not really have access to the directory drive. I tried it on my personal computer and it showed the run-time error.
My code is working fine when I am using our company computers which have access to the directory drive. And it displays the message box "unable to access" if I try to change the folder name to make it inaccessible (for troubleshooting purposes).
What I am trying to do is actually display a message box just in case the computer used do not have any access to the directory.
I tried searching around, tried using "", 0, and vbNullString. But no success. Thank you in advance for any help.
'Check if all fields are filled up.
If Wbb.Sheets("Report").TextBox3.Value = "" Then
MsgBox "Please check missing data."
Else
'Check if drive is accessible, if not prompt a message
If Dir(filePath1, vbDirectory) = "" Then 'this is where the run-time error is pointing at
MsgBox "Unable to access drive. Please save file manually."
Exit Sub
Else
'Check if folders exists in drive. If does not exist, create folders.
If filePathCheck <> "" Then
aDirs = Split(filePathCheck, "\")
If Left(filePathCheck, 2) = "\\" Then
iStart = 3
Else
iStart = 1
End If
sCurDir = Left(filePathCheck, InStr(iStart, filePathCheck, "\"))
For i = iStart To UBound(aDirs)
sCurDir = sCurDir & aDirs(i) & "\"
If Dir(sCurDir, vbDirectory) = vbNullString Then
MkDir sCurDir
End If
Next i
End If
End If
Dir() throws an error if the left part of the directory does not exist. However the FileSystemObject simply returns False without throwing an error.
Public Function FolderExists(ByVal Path As String) As Boolean
With CreateObject("Scripting.FileSystemObject")
FolderExists = .FolderExists(Path)
End With
End Function
No reference the the Scripting.Runtime required.
Going off of what #Jeeped said in your comments, use Error Handling - [1] - [2] - [3]
On Error GoTo ErrHandler
Exit Sub
ErrHandler:
Select Case Err.Number
Case 52
MsgBox "~"
' Possibly pop up a save dialog if you desire
Err.Clear
Resume Next
Case Else
MsgBox "!"
Exit Sub
End Select
I launch Python through a VBA macro. I want a proper error message if the Python path isn't good.
I use this macro on 2 different computers, and the Python paths are not the same on those 2 computers. The 2 paths are on 2 differents Cells name path_Python and path_Python_2
Here is my code :
Function launchPython() As Boolean
Dim pathScript As String
pathScript = [path_files] + "code.py"
On Error GoTo err
Shell [path_Python].Value & " " & pathScript
launchPython = True
Exit Function
err:
On Error GoTo err2
Shell [path_Python_2].Value & " " & pathScript
launchPython = True
err2:
launchPython = False
MsgBox "Error: please check Python paths"
End Function
Problem is, when 2 the paths are not good, instead of going to err2, I have a VBA error message blocking on
err:
On Error GoTo err2
Shell [path_Python_2].Value & " " & pathScript
How can I solve this ?
Thank you very much
Instead of trying to shell a command to a potentially missing path, I would check that a file exists and try that. You can use one of many functions such as FileExists in http://allenbrowne.com/func-11.html, or just check that dir$ returns non blank.
Dim Path as string
path = path_python
if dir(path) = "" then
path = path_python2
if dir(path) = "" then err.raise
end if
shell path & " " & pathScript
There is some old legacy vbscript code we have that needs some sort of error handing in it. Having never used vbscript before, I'm at a total loss. Here is the code:
set objBL = CreateObject("SQLXMLBulkLoad.SQLXMLBulkload.4.0")
objBL.ConnectionString = "connectionstring"
objBL.KeepIdentity = false
objBL.ErrorLogFile = "E:\code\Acquity\WebOrderImport\logs\error.log"
Set fso = CreateObject("Scripting.FileSystemObject")
Set parentfolder = fso.GetFolder("E:\textdata\Acquity\AcquityWebOrders")
Set logfile = fso.OpenTextFile("E:\code\Acquity\WebOrderImport\logs\import.log",8)
count = 0
For each folder in parentfolder.subfolders
logfile.writeline count & " files"
logfile.writeline "Processing " & folder.name & " ***********************************" & now()
count = 1
For Each file in folder.files
If left(file.name,6) = "Order_" then
If left(file.name,13) = previous then
logfile.writeline "!!!!! SKIPPING file " & file.name & "!!!!! DUPED ORDER ID"
Else
logfile.writeline "reading " & file.name
objBL.Execute "E:\code\Acquity\WebOrderImport\acq_WebOrder_import.xsd", file.path
count=count+1
End If
previous = left(file.name,13)
End If
Next
Next
set objBL=Nothing
logfile.writeline "Done!"
Set logfile = nothing
Set parentfolder = nothing
set fso = nothing
I'm pretty sure this line:
bjBL.Execute "E:\code\Acquity\WebOrderImport\acq_WebOrder_import.xsd", file.path
keeps throwing exceptions, and I need the code to keep running when it hits an error, rather than stopping. How can I do this?
To ignore errors, add On Error Resume Next before the part that can cause them. To disable the effect of "resume next", use On Error Goto 0.
For a quick and (very) dirty way to get the code to keep running, you can add On Error Resume Next to the top of the file, and execution will happily carry on when it hits an error.
I have a little practice with this technology, but AFAIK vbscript has only one way to handle runtime-exceptions: On Error Resume Next.
You can read these articles: MSDN article and more helpful for me about handling and notifying.