FileCopy gives Error 53 File Not Found - vba

The Problem:
As stated above, I have a line of code, FileCopy String5, String6, that is giving Error 53: File Not Found. I have determined that the error is occurring with String6. I need another pair of eyes to help me find the error.
What I've Tried:
Printing String6 to a cell to make sure it is correct
Copying String6 into Windows Explorer and Windows-->Run (after deleting the file name, it hasn't been created yet due to the macro error) to make sure they open the folder correctly
Used Dir function to double check that Excel can see the copyto directory after I've made it
Because the files about to be copied come from a folder that was unzipped prior to the code, adding a 1 second wait in case the new files somehow hadn't been detected (basically trying everything now)
I'm open to any suggestions. Here's an updated section of my code in case it helps, and I'd be happy to post the whole thing as well:
'File Manipulation
'Find a file in StrDir1 with String2 extension, "*.dat"
String4 = Dir(StrDir1 & String2)
Do While String4 <> ""
'Save the complete path of the file found
String5 = StrDir1 & String4
For Loop1 = LBound(Array1) To UBound(Array1)
'Array1 has file identifiers in it that identify who the file belongs to for later separation and folder placement
If InStr(String5, Array1(Loop1)) Then
'We found a file with the identifier, save the future complete path of the copied file
String6 = StrDir1 & Array2(Loop1) & String4
'Create the containing folder where the file will be copied if it does not already exist
String10 = vbNullString
On Error Resume Next
'Check if the folder already exists
String10 = Dir(StrDir1 & Array2(Loop1), vbDirectory)
On Error GoTo 0
'If it doesn't exist, create it
If String10 = vbNullString Then
MkDir StrDir1 & Array2(Loop1)
End If
'String8 is the file type, it was determined earlier
If String8 = "997" Then
String7 = "\\(directory)\" & String4
'This works, which makes me think the problem is String6.
Object2.CopyFile String5, String7
'For testing purposes
ThisWorkbook.Sheets(1).Cells(1, 1).Value = String5
ThisWorkbook.Sheets(1).Cells(2, 1).Value = String6
String10 = Dir(StrDir1 & Array2(Loop1), vbDirectory)
'Back to the real code
'When these lines are commented, Error 53, file not found. When uncommented, Error 76, path not found.
' String5 = " & String5 & "
' String6 = " & String6 & "
'Error occurs here
Object2.CopyFile String5, String6
Kill String5
String4 = Dir(StrDir1 & String2)
'code continues
To reiterate, the error occurs on the Object2.CopyFile String5, String6 line of the above code.
Here are String5 and String6 at the time of error, in case it helps anyone. These values are copied from Cells 1,1 and 2,1:
String5: \\extremely long directory\extremely long file name.ext
String6: \\extremely long directory\extremely long file name.ext
Update: I switched to fso.copyfile and I also tried adding quotes around my strings to avoid any problems with the directories containing spaces. When I added quotes, the error changed to Error 76, path not found. Does this help troubleshoot my code?
(I also added a few more lines to my code snippet to hopefully demonstrate this isn't a Dir() problem to the best of my knowledge, but since I am new to Dir(), Tim could still be right.)
Update 2: I think String6 is too long. I'm using the following code to test but Excel keeps crashing after successfully copying the file when I try to run it. Is there something I need to know about FSO to prevent that?
Sub M2Pathtester()
Dim String5 As String
Dim String6 As String
Dim Object2 As Object
Set Object2 = CreateObject("scripting.filesystemobject")
String5 = ThisWorkbook.Sheets(1).Cells(1, 1)
String6 = ThisWorkbook.Sheets(1).Cells(2, 1)
Object2.CopyFile String5, String6
End Sub
Final Update:
Yes, the string was too long. Excel still repeatedly crashes (after successfully copying) using the fso.copyfile method, but when I reverted back to FileCopy, it worked smoothly.

I don't see any obvious reason that you should be getting an error 53 for the destination file. Some sources indicate that FileCopy can be quirky with spaces in the path, but that really should be giving an error 52 if that's the case. I found one other report of somebody claiming that they needed to stop hiding know file extensions in the destination folder to avoid an error with FileCopy, but I'm not sure I'm buying that one.
I'd make sure that you have the appropriate permissions in the folder you're writing to, and use the Scripting.FilesystemObject to perform the copy instead - it's typically more robust:
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile String5, String6

The answer was that String6 exceeded the maximum character length. So be warned that that is a possibility when getting Error 53 or Error 76 when using FileCopy or fso.copyfile.
Note: Because of my inexperience with FSO, this might not be exactly/technically correct, but I hope it informs you enough to get you on the right path if you're stuck.

Related

VBA FileExists and Sharepoint

I'm running into issues trying to pull info from files stored in Sharepoint.
Namely, FileExists isn't working and Overwrite file doesn't seem to be working either.
There was a discussion here, but few answers -> posting this question again in hopes some things have changed
My code runs like this:
strFileExists = Dir(Filepath & Filename)
And returns: File path not found -> I checked the path and even opened a file and recorded the macro to make sure it was the same file path without issue, but it appears DIR() is the issue.
The business dept I'm working with is entirely switching over to Sharepoint so hoping there's a straightforward solution without setting up network shares or doing C/personal/OneDrive things
You can navigate and look for files on OneDrive like this
Sub check_File_Exists()
Dim path As String
Dim strType As String
Dim file As Variant
Dim yourFile As String
'replace uname with your user name
path = "C:\Users\uname\OneDrive\"
strType = "*txt"
yourFile = "test.txt"
file = Dir(path & strType)
Do While (file <> "")
If file = yourFile Then
Debug.Print ("File: " & file & " found!")
Exit Do
End If
file = Dir
Loop
End Sub
Hope it helps

Copy file with progress bar bypass file replacement confirmation

This is a follow up to this question and great answer:
Copy files with progress bar
So I added the code from Siddharth Rout's answer and it does exactly what I want to happen with a minor exception. When I copy the files, I am looping through each file in the directory and copying it up as long as it is not *List.xml. Because I am replacing an existing library the 97% of the documents are pre-existing and I get prompted to replace existing documents each time.
Is there a way to get it to prompt me to choose to replace for all files? Do I need to reformat/structure the sequence of my code?
Function UploadToSharepoint(Folderpath As String, Foldername As String, Filenames() As String, SharepointLinks() As String) As Boolean
'upload file to sharepoint library based on the folder name
Dim SharePointLib As String
Dim LocalAddress As String
Dim DestinationAddress As String
Dim xCounter As Long
On Error GoTo loadFailed
Pickafolder:
Folderpath = FolderPick
Foldername = Left(Folderpath, Len(Folderpath) - 1)
Foldername = RIght(Foldername, Len(Foldername) - InStrRev(Foldername, "\"))
Select Case Foldername
Case "OPSS", "SSP", "OPSD", "MTOD", "SSD"
SharePointLib = "\\my.company.com\Subsite\" & Foldername & "\"
Case "West", "Eastern", "Northeastern", "Northwestern", "Head Office"
SharePointLib = "\\my.company.com\Subsite\NSP\" & Foldername & "\"
Case "NSP", "NSSP"
MsgBox "Pick the NSP regional sub folder: West, Eastern, Northeastern, Northwestern, Head Office"
GoTo Pickafolder
Case Else
MsgBox "Inappropriate directory to upload from. Please select one of the CPS download directories"
GoTo Pickafolder
End Select
Filenames = GetFilesDir(Folderpath)
ReDim SharepointLinks(LBound(Filenames) To UBound(Filenames))
For xCounter = LBound(Filenames) To UBound(Filenames)
LocalAddress = Folderpath & Filenames(xCounter)
DestinationAddress = SharePointLib & Filenames(xCounter)
'**********************************************************
Call VBCopyFolder(LocalAddress, DestinationAddress)
'**********************************************************
SharepointLinks(xCounter) = "#http:" & Replace(DestinationAddress, "\", "/") & "#"
Next xCounter
UploadToSharepoint = True
Exit Function
loadFailed:
UploadToSharepoint = False
End Function
And by the looks of things I am not excluding the file I was referring to earlier...must be doing that else where.
Update
Based on comment received at the linked question, the solution is to declare a public constant at the start:
Public Const FOF_NOCONFIRMATION As Long = &H10
and then in the copy procedure change the line of code to:
.fFlags = FOF_SIMPLEPROGRESS Or FOF_NOCONFIRMATION
Now, this does solve the problem of being constantly asked to confirm the replacement. I am very happy about this. The problem now is the progress window displays for the first file to be copied then disappears but fails to reappear for subsequent files. The remaining files still get copied and the prg carries on like it's supposed to. The whole point of the progress bar though was to let people know that "THINGS" were still happening in the background and now that is not happening. Is there something I need to adjust?
Update 2
After running my code and choosing a source directory on the network drive instead of the local computer, the copy window is popping up for every single file like I was expecting. I notice that sometimes the progress bar closes before reaching 100%. This leads me to believe that since the file sizes are so small that when it is copying from my local drive to sharepoint, the operation completes so fast that it does not have time to draw and update the progress window before its time to close it.

VBA open a csv file with unknow file name

I have got a rather simple question as i think but i couldnt find out it myself.
I want to open a csv File in a defined binder but with an unknow filename. I would asume that it should work with simply "path/*.csv" however it is not :( The errormessage says "Wrong Filename". Do i need to use something else in VBA.
path = ActiveWorkbook.path & "\input\"
Open path & "*.csv" For Binary As #1
The above code does not work for me :( The CSV is called xyz.csv
path = ActiveWorkbook.path & "\input\"
Open path & "xyz.csv" For Binary As #1
The code above is working however i have fix added the csv filename, which in this case is xyz.
Somebudy knows how to get that thing to work?
Cheers and thx for your time
Marc
Dim path As String
Dim csvFiles As String
path = ActiveWorkbook.path & "\input\"
csvFiles = Dir(path & "*.csv")
Do While Len(csvFiles) > 0
Debug.Print csvFiles
csvFiles = Dir
Loop
You can use the Dir() Function to check the files in your folder if you don't know the filename.

Shell.namespace not accepting string variable, but accepting string itself

I have a code, in which I want to loop through files in a folder, check their built-in or custom document properties (without opening them), and later open those, which are meant to be open.
To do this, I'm using Shell and to set the folder I'm using Shell.Namespace.
The problem is with the Namespace, I guess. When I use a variable strSuborCesta for the path it doesn't work. When I print the variable strSuborCesta into immediate window and use the printed string inside the Shell.Namespace("....") it does work.
By it doesn't work I mean I get:
run-time error : 91 Object variable or With block not set
when I try to loop through the files in folder (which is not set in that case, so I understand why the error occurred, but don't understand why it's not accepting a string variable)
The path is correct in both ways. But I need it to be a variable, not a hardcoded string.
Where do I error?
Is there any better way, to check document properties (like comments, title, author, etc.) without opening the Excel files?
Below is the section (currently just in testing phase) that is giving me a hard time.
str[name of variable] variables are string data types. sFile, oShell, oDir are as Variants
'--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'get a root path
strPriecinokCesta = ThisWorkbook.Path 'path to this file
strPriecinokCesta = Left(strPriecinokCesta, Len(strPriecinokCesta) - (Len(strPriecinokCesta) - InStrRev(strPriecinokCesta, "\"))) 'root path is one level above this file
'--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'input files are in a subfolder
strSuborCesta = strPriecinokCesta & "Zdroje\"
strSuborPripona = "Formular_BD_kotolna*.xls" 'name of a file with extension
strSuborNazov = Dir(strSuborCesta & strSuborPripona) 'actual file name
'--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'get access to the file system
Set oShell = CreateObject("Shell.Application")
Set oDir = oShell.Namespace(strSuborCesta) '<----this will produce an error. In contrast to using a hard coded string. Why?
For Each sFile In oDir.Items '<---- run time error 91 occurs on this line
Debug.Print test & " : " & oDir.GetDetailsOf(sFile, 24) 'comments
Next
Variable strSuborNazov should be a variant
Dim strSuborNazov as variant
oShell.Namespace(strSuborNazov)
https://msdn.microsoft.com/en-us/library/windows/desktop/bb774085(v=vs.85).aspx

How do I fix my VBA renaming program's 0 return?

I am open to completely changing this code. The link to the original is in the code itself. I'm sure there's an easier way to do it and the actual renaming part is NOT my own code, so I will redo it so it isn't plagiarizing. I can't use a batch file renamer to do it; I need to make it myself to stay out of trouble with legal :) No grey area!
Anyways, after a few dozen attempts on my own, I finally caved and grabbed this code online that is supposed to rename the files I specify. I edited it to fit my parameters and assigned variables/directories. When I run it, however, I always get a return of zero and the files are not being renamed. The one thing I could think of is that this directory is going to the full path name of the folder instead of the part after the last "\". But I'm not sure how to fix this either. I thought about trying to tell it to only tell it to pull, say the last 8 characters of the string, but that won't work either as these string lengths will vary anywhere from one character to 20 or so characters.
Here is my code:
Private Sub Apply_Click()
'This will initiate Module 1 to do a batch rename to find and replace all
'Module 1 will then initiate the resolving links process
Dim intResponse As Integer 'Alerts user to wait until renaming is complete
intResponse = MsgBox("Your folders are being updated. Please wait while your files are renamed and your links are resolved.")
If intResponse = vbOK Then 'Tests to see if msgbox_click can start a new process
Dim i As Integer
Dim from_str As String
Dim to_str As String
Dim dir_path As String
from_str = Old_Name_Display.Text
to_str = New_Name.Text
dir_path = New_Name.Text
If Right$(dir_path, 1) <> "\" Then dir_path = dir_path _
& "\"
Old_Name_Display = dir$(dir_path & "*.*", vbNormal)
Do While Len(Old_Name_Display) > 0
' Rename this file.
New_Name = Replace$(Old_Name_Display, from_str, to_str)
If New_Name <> Old_Name_Display Then
Name Old_Name_Display.Text As New_Name.Text
i = i + 1
End If
' Get the next file.
Old_Name_Display = dir$()
Loop
MsgBox "Renamed " & Format$(i) & " files. Resolving links now."
If intResponse = vbOK Then
MsgBox "You selected okay. Good luck coding THIS." 'Filler line to test that next step will be ready to initialize
Else: End
End If
Exit Sub
'Most of batch renaming process used from VB Helper, sponsored by Rocky Mountain Computer Consulting, Inc. Copyright 1997-2010; original code available at http://www.vb-helper.com/howto_rename_files.html
End Sub
Does anyone have another theory on why I get a 0 return/how to fix that potential above problem?
It doesn't look like the directory is getting referenced in the rename.
Change
Name Old_Name_Display.Text As New_Name.Text
to
Name Dir_Path & Old_Name_Display.Text As Dir_Path & New_Name.Text