VBA error 1004 Sorry, we couldn't find - vba

I've receive the above error for the following code:
Dim location_results As String
location_results = Worksheets("merging").Range("B1").Text 'absorbing the initial computation results folder
file_results = Dir$(location_results & "\" & "*" & NBDID & "*" & ".*") 'checks if there is a file with NBDID in the "location results folder
If (Len(file_results) > 0) Then
Worksheets("list").Range("D" & i).Value = file_results
Else
MsgBox (NBDID & " result not found")
End If
'problem todoB:
lineD:
Dim shortlocation As String
shortlocation = ThisWorkbook.Path & "\megaresults\" & file_results
On Error GoTo lineD
'Workbooks(shortlocation).Open
Set InputFile = Workbooks.Open(FileName:=shortlocation)
'Set InputFile = Workbooks.Open(location_results & file_results)
Set OutputFile = Workbooks.Open(location_merger & file_merger)
On Error GoTo 0
The error is raised on the line:
Set InputFile = Workbooks.Open(location_results & file_results)
and on the line:
Set InputFile = Workbooks.Open(FileName:=shortlocation)
Now googling that error, nearly everyone has an issue that the file they are trying to open is not in the parents-workbook folder, or that they did not preappend their path to the file specification.
I have done that however, and the path is validated, both manually by me checking whether the file is in the folder, as well as with:
If (Len(file_results) > 0) Then
Worksheets("list").Range("D" & i).Value = file_results
Else
MsgBox (NBDID & " result not found")
End If
, the file exists, and the total path, including file name and extention is 222 characters long. It also contains spaces.
But I can't find any reason for it to return as an error. On top of that, the on error goto lineD does not function, it still pops up with a message that does not allow continuing of the code.
Could someone point out my mistake to me, or give me a solution that would work?
Kind regards.

Related

How to skip an iteration that has an error?

I created a nice macro for CATIA V5, that make some geometrical parameters increase in a loop, and save the file for each case.
Unfortunately, there are some combinations that won't work and create errors in catia itself.
Until know I used On error Resume Next.
But I would prefere that if there is an error, it saves it as the previous, errorless, file
here is a part of my code :
For i = 1 To 10
strParam2.Value = Val(i) * 1
part1.Update
On Error Resume Next
folderpath3 = folderpath2 & "\" & "file" & i
MkDir folderpath3
name = folderpath3 & "\" & "file" & i
partDocument1.ExportData name, "CATPart"
If someone has an idea, I would be grateful!
matthieu
You should save a last known correct value if the part can be updated and then use this value if you have an error on Update. You should initialize lastCorrectValue to a value which will always work. I don't know what type do you use, so I just initialized it to an Integer with the value of 5.
Dim lastCorrectValue as Integer
lastCorrectValue = 5
For i = 1 To 10
strParam2.Value = Val(i) * 1
On Error Resume Next
part1.Update
If Err = 0 Then GoTo Continue
strParam2.Value = lastCorrectValue
part1.Update
Continue:
lastCorrectValue = strParam2.Value
folderpath3 = folderpath2 & "\" & "file" & i
MkDir folderpath3
name = folderpath3 & "\" & "file" & i
partDocument1.ExportData name, "CATPart"
Next i

What would cause VB6 to throw an error that is not handled by the error handler?

I have a few lines of code wrapped in two write log events. I know that the first part of the code is happening because I can see the first entry of the log that says the process has started but the entry that says the process completed is not being written. Somewhere in the code an error is being thrown but the error handler is not catching it for some reason. I've tried checking the event viewer for any logs about my application that Windows may have written, like it causing a crash or Windows closing it for some reason but there's nothing there. Is there a way that VB6 would skip an error handler and if so, how could I find evidence of it?
My code looks something like this:
On Error GoTo ErrorHandler
Dim fso As FileSystemObject
Dim DirPattern As String
Dim FileName As String
Dim DaysOld As Integer
' Init log name to ensure Today's value will be put in there
g_PurgeLogName = ""
Call WriteToLog("Purging of Text Files Started")
sql = "SELECT * FROM [Text File Purge Profiles] " & _
"WHERE User = '" & g_User & "' " & _
"ORDER BY ProfileName;"
Dim rs As ADODB.Recordset
Set rs = ic.RsReadOnly(cnMF, sql)
With rs
Do While Not .EOF
Set fso = New FileSystemObject
' create dirPattern to use with "Dir" command
DirPattern = fso.BuildPath(!PurgePath, !FileMask)
' get first file matching this pattern
FileName = Dir(DirPattern)
Do While Len(FileName)
FileName = fso.BuildPath(!PurgePath, FileName)
' how many days ago was this file created?
DaysOld = DateDiff("d", fso.GetFile(FileName).DateCreated, Now)
If DaysOld > !RetainDays Then
Debug.Print "Deleting " & FileName
fso.DeleteFile FileName, True
DoEvents
End If
' get next file matching this pattern
FileName = Dir
Loop
.MoveNext
Loop
.Close
End With
Call WriteToLog("Purging of Text Files Completed")
Set fso = Nothing
Set rs = Nothing
Exit Sub
'=============
ErrorHandler:
'=============
Call MsgBox2("An error occured while trying to process the Text File purge" & _
vbLf & vbLf & err.Number & ": " & err.Description, vbCritical)
Call WriteToLog("Text File Purge did not complete")
Call WriteToLog(vbTab & err.Number & ": " & err.Description)
Call ClearScreen
Call err.Clear
I can see that there could be issues with deleting files the program doesn't have permission to access or that there could be an issue with the query somehow but as far as I can tell, any problems that could arise should be handled by the error handler and the log would still have more text than the "process started" bit.

VBA Access 2010 DIR results in empty string

I have the following code:
Private Sub cmdExportTERNAME_Click()
On Error Resume Next
Me.MsgFld = "Please wait... exporting TERNAME file."
Dim expLoc As String
Dim xFile As String, myFile As String
Dim myFlag As Integer
expLoc = "I:\Investigative Names\" ' PRD
xFile = Dir(expLoc & "NAME - ForUpload.txt", vbDirectory)
myFile = "NAME-ForUpload.txt"
myFlag = StrComp(xFile, myFile)
If myFlag <> -1 Then
Kill expLoc & "NAME-ForUpload.txt"
End If
' Export text files for upload
DoCmd.TransferText acExportFixed, "SpecTERNAME", "qry_TERNAME", expLoc & "NAME-ForUpload.txt"
xFile = Dir(expLoc & "TNAME-ForUpload.txt")
myFile = "NAME-ForUpload.txt"
myFlag = StrComp(xFile, myFile)
If myFlag <> -1 Then
GoTo ContinueProcessing1
Else
MsgBox "The program was not able to export the NAME file for upload." & Chr(13) & Chr(13) & "Please notify IS Department.", vbCritical, "ERROR MESSAGE BOX"
GoTo exitRTN
End If
ContinueProcessing1:
exitRTN:
End Sub
So I have 2 more of these subroutines with different text files which work fine but this block of code doesn't find xFile, it return a empty string which causes the program to display the message box error. I can't figure out why the same code with different text file works before it reaches this code. The weird thing is it sometimes finds the correct xFile name in debug mode but not when run normally. Can someone help me figure this out?
Thanks

Detailed QueryTables Error Handling

Good Afternoon,
I am looking for a way to handle QueryTable Errors. I have looked at other questions on google and stackoverflow, however they do not appear to answer the specific question i am trying to ask.
Basically, is there a way to determine what the specific error was when handling a QueryTables error?
Code:
On Error Goto queryError
With Activesheet.QueryTables...
....
End With
queryError:
Msgbox("There was an error with the QueryTables. The reason for the error was: " & myError)
Is there a way to set myError to give more details specific to what the problem was, even if it means selecting some sort of status code? eg
QueryTables.StatusCode...
or something?
Thanks in advance.
How to handle errors:
Excel VBA doesn't supportTry Catch Finally. Instead, it uses On Error GoTo
For full control over error-handling in Excel you must use labels (which always end in a colon).
In this example, the two labels are:
tryAgain:
queryError:
Assume that the Query Table being created is from a text file that looks something like:
When you first run the routine, the user is prompted for three inputs:
Filepath
New Table Name
Cell (i.e. Range) to paste into
If an error occurs on any of these inputs, the code will immediately go to the label queryError:
So, say the user didn't enter in a valid filepath, it would look something like this:
If the user clicks Yes (to try again), then Resume tryAgain will take the code back up to that label and go through it all over.
Pay attention to the Select Case at the end. This is how you can control how you want to handle specific errors.
Here is the code to paste in a module:
Option Explicit
Sub CreateQueryTable()
'Assign values to these variables by prompting user with Input Boxes
Dim filepath As String
Dim qryTableName As String
Dim startCellForTable As Range
'These variables are used in the error handling prompts
Dim Msg As String
Dim Ans As Integer
'If an error occurs, code will go to the label `queryError:`
On Error GoTo queryError
tryAgain:
'Prompt user for the filename of the .txt file to use as QueryTable Source
filepath = InputBox("Please enter filepath of text file to use as the source")
'Prompt user to name the new Query Table
qryTableName = InputBox("Please enter name of Query Table")
'Prompt user for the cell to put table at
Set startCellForTable = Application.InputBox(Prompt:="Please select a cell where you would like to paste the table to", Type:=8)
'If user hits OK, check to see that they at least put something as a value
If filepath <> "" And qryTableName <> "" And startCellForTable <> "" Then
'format filepath variable so can pass it as argument to QueryTables.Add
'Trim any leading or trailing spaces from qryTableName
filepath = "TEXT;" & filepath
qryTableName = Trim(qryTableName)
End If
'Create QueryTable at Range("A1")
With ActiveSheet.QueryTables.Add(Connection:=filepath, Destination:=Range(startCellForTable.Address))
.Name = qryTableName
.Refresh BackgroundQuery:=False
End With
'If there are no errors, exit the procedure (so the `queryError:` code won't execute)
Exit Sub
queryError:
Msg = ""
'Say that an error occured
Msg = Msg & "An error occurred with the Query Table. " & vbNewLine & vbNewLine
'Use Excel's built-in Error object (named `Err`) to show error number and description of error
Msg = Msg & Err.Number & ": " & Error(Err.Number) & vbNewLine & vbNewLine
Select Case Err.Number
'Type mismatch
Case 13
'Object required
Case 424
Msg = Msg & vbNewLine & "Please check that a valid range was selected" & vbNewLine
'Application defined or Object defined error
Case 1004
Msg = Msg & vbNewLine & "Please check that this filepath is correct: " & vbNewLine & vbNewLine & filepath & vbNewLine
Case Else
End Select
'Prompt user to Try Again
Msg = Msg & vbNewLine & vbNewLine & "Try again?"
Ans = MsgBox(Msg, vbYesNo + vbCritical)
'If user says Yes, clear the error, and resume execution of code at label `TryAgain:`
If Ans = vbYes Then Resume tryAgain
End Sub

VBscript: Verifying that a file has been completely copied/error handling

I am trying to add something to my script that will let me know if a file that I am copying has been fully copied.
Basically I am zipping up a bunch of files and then sending them to a mapped drive on the network. Then I have my script deleting the files in the original location once they have been successfully copied over. The script works perfectly fine but I just need to add in some error handling that will let me know if the copy was not completed successfully.
I have never used any error handling in vbscript as I am only about a week into this so any help would be greatly appreciated. Let me know if I need to explain anything more in depth. My script can be found below:
Option Explicit
Dim sDirectoryPath, sDestinationPath, sOutputFilename, Shell, sFileExt, sFilePrefix
shell = WScript.CreateObject("WScript.Shell")
'Specify Directory Path where files to be zipped are located
'Specify destination for zipped files
'Specify file extension name to look for
'Specify prefix of filename to look for
sDirectoryPath = "C:\Testscripts\"
sDestinationPath = "C:\Script\files\outzips\"
sOutputFilename = shell.ExpandEnvironmentStrings("%COMPUTERNAME%")
sFileExt = ".evtx"
sFilePrefix = "Archive*"
Dim Command, RetVal
Dim d : d = Date()
Dim dateStr : dateStr = Year(d) & "-" & Right("00" & Month(d), 2) & "-" & Right("00" & Day(d), 2)
Dim t : t = Time()
Dim timeStr: timeStr = Hour(t) & "-" & Right("00" & Minute(t), 2) & "-" & Right("00" & Second(t), 2)
Command = """C:\Program Files\7-zip\7z.exe"" a " & sDestinationPath & sOutputFilename & "-" & dateStr & "-" & timeStr & ".zip " & sDirectoryPath & sFilePrefix & sFileExt
RetVal = Shell.Run(Command,0,true)
Wscript.Sleep 2000
Dim objFso
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Copy files from one path to another
objFSO.CopyFile "C:\script\files\outzips\*.zip" , "G:\CopyTestFolder\"
If err.Number <> 0 Then
WScript.Echo "An error occured copying this file, re-attempt copy"
Else
WScript.Echo "No errors occured, copy successful"
End If
On Error GoTo 0
'After files have been successfully zipped and copied specify where to delete
'old zip files from, and the local archived folder path to delete
objFSO.DeleteFolder("C:\Script")
'Can either delete entire archived folder, or just .zip files in folder
objFSO.DeleteFile("C:\Testscripts\Archive*.evtx")
'Location where original files are that need to be deleted after the copy is successful
Use the 't' command on 7-zip to verify integrity. If '0' ok, else error.
For example:
Set myshell = WScript.CreateObject("WScript.Shell")
Dim cmd, result
cmd = """C:\Program Files\7-zip\7z.exe"" t C:\NOT_a__valid_zip_file.zip"
result = myshell.Run(cmd,0,true)
Wscript.Echo "Not a valid zip file: " & result
cmd = """C:\Program Files\7-zip\7z.exe"" t C:\a_valid_zip_file.zip"
result = myshell.Run(cmd,0,true)
Wscript.Echo "A valid zip file: " & result
Output:
PS> cscript.exe .\7z.vbs
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.
Not a valid zip file: 2
A valid zip file: 0