File not found - error 53 when trying to rename file that exists - vba

Very weird as this code was running last night!!
I haven't changed anything and now it is failing as an error 53 - file not found.
Dim oldFilePath As String
Dim newFilePath As String
FolderPath = "C:\Users\ME\Documents\Scans\"
NewFileName = "Invoice " & InvID & " For " & LName & ", " & FName & ", " & ClaimNo
oldFilePath = FolderPath & Filename
newFilePath = FolderPath & NewFileName & ".pdf"
Debug.Print oldFilePath
Name oldFilePath As newFilePath <--FAIL HERE
The debugs are coming out:
C:\Users\ME\Documents\Scans\ZephyrClaims20181018161309042577.pdf
Which is correct.
This file exists and when I copy the debug code into a windows explorer address bar and press enter, then file opens in acrobat!
As mentioned this was working before.
This is a function which cycles through specific files in a folder, renames them and then loops.
The list of files are filenames only in an access DB, and then you can see the folder path there, which does have the "\" on the end.
Totally stuck if anyone has an idea!
I ahve also tried DIM as Variant, which had no effect.
I find it just so weird that this has worked for about 20 files and now is failing.

The error was caused by the NEW file name having illegal characters in it as per user #Andre comment!!!

Related

code not working: Copy file From one directory to another with vba

I have write a VBA code to copy file from one directory to another; but I can't figure out why it is not working. Any ideas? I know how to do it using FileSystemObject but I will like to learn - doing it with SHELL.
Sub copy_file()
Dim dirPath As String, srcFile As String
dirPath = "E:\Download\"
srcFile = ThisWorkbook.Path & "\" & ThisWorkbook.Name
Shell ("cmd /c copy /y """ & srcFile & " " & dirPath & """")
End Sub
You're over-complicating.
You don't need to use Shell and go through the command line for this.
There's a built-in command: FileCopy
Example
This example uses the FileCopy statement to copy one file to another. For purposes of this example, assume that is a file containing some data.
Dim SourceFile, DestinationFile
SourceFile = "SRCFILE" ' Define source file name.
DestinationFile = "DESTFILE" ' Define target file name.
FileCopy SourceFile, DestinationFile ' Copy source to target.
Read the documentation for FileCopy at the source.
I'd also suggest taking a few minutes to read through all the standard VBA objects and their available methods/functions/properties/etc to get an idea of what kind of tasks have built-in functionality with VBA and/or Office.
Here is the main page of the official documentation for Office VBA.
srcFile is the same file that you are using to hold your vba code, and therefore that file is already open. In that case Windows shell copy command will not work, by design.
You can duplicate your opened source file with the ActiveWorkbook.SaveAs method.
Further reading: How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?
Further problem: your active workbook will immediately renamed, therefore you have to close it. In order to avoid having save as dialog before exit, read that tutorial: https://support.microsoft.com/en-us/help/213428/how-to-suppress-save-changes-prompt-when-you-close-a-workbook-in-excel
Shell ("cmd /c copy /y """ & srcFile & " " & dirPath & """")
Quotes issue. You should be check your path and try this code below:
Sub copy_file()
Dim dirPath As String, srcFile As String
dirPath = "E:\Download\"
srcFile = ThisWorkbook.Path & "\" & ThisWorkbook.Name
MsgBox "cmd /c copy /y " & srcFile & " " & dirPath
Shell ("cmd /c copy /y " & srcFile & " " & dirPath)
End Sub

Trying to add an attachment to an email from excel where only the first part of the file name is known

I have a macro which I am using to attach an automatically generated file to an email on a daily basis.
The filename is required to be a certain format which includes the date and time, and as this is automatic, only the date will be known inherently (without manually checking the file).
I am using .Attachments.Add and format(date... etc.) to get the second part of the file name.
The first part is a number and a word which don't change
but the third part (shown as "*.csv" below) is the bit that is causing the issue.
I have tried to substitute * like I saw on a forum but it where it seemed to work in that example it is not working for me. Am I missing something?
.Attachments.Add ("G:\AML, CFT & Sanctions\Sanctions\KYC6 Person & Organsation Reports\" & Format(Date, "yyyy") & "\" & Format(Date, "mmmm") & "\65436546_Test_" & Format(Date, "yyyymmdd") & "*.csv")
As #Kostas suggested, you can find files by a glob with the Dir function. Note that it only returns filename, without a path.
Do handle the case when nothing or more than one file matches the pattern. (My code produces an error in these cases; error codes are taken from http://www.halfile.com/vb.html .)
Dim date_ As Date, pattern, dir_, filename As String: date_ = Date
dir_ = "C:\Users\Ivan\Documents\test & test\" & _
Format(date_, "yyyy\\mmmm\\")
pattern = "65436546_Test_" & Format(date_,"yyyymmdd") & "*.csv"
filename = Dir(dir_ & pattern)
If Len(filename) = 0 Then Error 53 'File not found
If Len(Dir()) <> 0 Then Error 58 'More than one matching file
<email>.Attachments.Add(dir_ & filename)
Build the file path first, test it and attach it if it's valid. As advised in comments, you need to supply a concrete file name, wildcards are not allowed.
Dim path_ As String, name_ As String, file_ As String
path_ = "C:\Some folder\"
name_ = "*.csv"
file_ = Dir(strPath & name_)
If Len(Dir(path_ & file_)) > 0 Then
.Attachments.Add path_ & file_
End If

Dir function does not find a file, even after copy pasting the path as a parameter

I've tried to get the Dir() function to work some time now using a rather complicated concatenated string, as seen below:
Dim Path as String
Path = Dir("PathToSubfolder\" & Year(Date) & "\" & MonthName(Month(Date)) & _
"\Production " & MonthName(Month(Date)) & "*.xlsx")
MsgBox Path
The message box prints nothing (it's just a blank Message Box). After trying to figure out whether I had mistyped the Path somehow, I opened up the correct file, and copypasted its actual Path from options, and subsequently performed: Path = Dir("PathToSubFolder\2016\June\Production June 2016.xlsx"), i.e. without any concatenation or anything, simply just the actual filepath and -name. However, Printing MsgBox Path returned nothing (NULL) again.
Does anyone have any clue as to why this wont work? I have used Dir quite extensively the last days from the same workbook (albeit not from the same module) without any issues.
Edit: Finally found a workaround. I simply made a variable with the path to the file, pathtoFile, and subsequently:
Dim pathtoFile As String
pathtoFile = "C:\Path.to.file\"
Path = Dir(pathtoFile & "*" & MonthName(Month(Date)) & "*")
Month(Date)
Will return a number, not a name. So you are passing the following argument:
PathToSubFolder\2016\6\Production 6 2016.xlsx
Which doesn't exist, hence you get a null string returned.
Try
Dim Path as String
Path = Dir("PathToSubfolder\" & Year(Date) & "\" & MonthName(Month(Date)) & _
"\Production " & MonthName(Month(Date)) & "*.xlsx")
MsgBox Path
the MonthName() method takes a number between 1 - 12 and returns the name of that month, which is what you need for your string.

Excel-VBA CopyFile Runtime Err 53 (File Note Found)

I am currently having an error with a vba script, tried to fix it but still gives an error as listed in the title.
The aim of the script is to copy file names based on an input form a worksheet and then copy them to a destination saving them with the current date in the name.
Set FSO = CreateObject("scripting.filesystemobject")
FILE = Sheet1.Range("G3").Value
FILE2 = Sheet1.Range("G4").Value
SourceFile = Source & "\" & FILE & ".xls"
DestFile = DestPath & "\" & FILE & " " & ShortDate & ".csv"
SourceFile2 = Source & "\" & FILE2 & ".xls"
DestFile2 = DestPath & "\" & FILE2 & " " & ShortDate & ".csv"
'Setsup Flag File
Dim oFile As Object
Set oFile = FSO.CreateTextFile(DestPath & "\OIS.FLAG")
oFile.WriteLine Format(Sheets("Sheet1").Range("C7").Value, "yyyy/mm/dd")
oFile.Close
FSO.CopyFile SourceFile, DestFile
FSO.CopyFile SourceFile2, DestFile2
Source is just set to "C:\Users\Data"
DestPath is just "C:\Users\updates"
When I run the script the first copy works, so SourceFile is copied, but then the runtime error occurs for the second one SourceFile2, but I've checked multiple times and the SourceFile2 Exists...
Any Tips, or something I'm missing? Also Checked other similar threads, and it's not because the string is too long?
If I input the whole name for SourceFile2 i.e "C:\Users\Data\file2.xls" then it works but I've checked the syntax a million times and seems to be fine, maybe a fresh pair of eyes will help, any suggestions would be massively appreciated :)

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