code not working: Copy file From one directory to another with vba - 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

Related

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

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!!!

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 :)

command line not working when run from vba

I'm trying to unzip a file via my VBA code. I'm using 7z command line to unzip the file. However the command works when run from normal command prompt but the same command is not working when run via VBA code.
Command:
"C:\Program Files\7-Zip\7z.exe" x "C:\Users\Public\AppData\Local\Temp\Sample.zip"
For further understanding, I'm trying to extract a docx file and that is why I am renaming it to .zip and then extracting.
Sub tst()
Dim MyFile As String, Outdir As String, Cmdstr As String
MyFile = Chr(34) & "c:\TMP\ratings.gz" & Chr(34)
Outdir = Chr(34) & "c:\tmp\0" & Chr(34)
Cmdstr = "c:\Program Files\7-Zip\7z.exe" & " e " & MyFile & " -o" & Outdir
Debug.Print Cmdstr
Call Shell(Cmdstr, 1)
End Sub
I've used this type of function (similar) to unzip the file.
Missing proper quoting, should be
Cmdstr = """c:\Program Files\7-Zip\7z.exe""" & " e " & MyFile & " -o" & Outdir
The Command Line Version of 7-Zip is 7za.exe rather than 7z.exe.
I'm not sure about running CLI applications with Shell method but next could work:
Cmdstr = "cmd /D /C " & """full path to 7za\7za.exe""" & " e " & MyFile & " -o" & Outdir
Edit. To retain folder structure, use 7z with x command rather than e command. While the e command copies all extracted files to one directory, the z command extracts files from an archive with their full paths in the current directory, or in an output directory if specified. So you could define Cmdstr as follows:
Cmdstr = """c:\Program Files\7-Zip\7z.exe""" & " x " & MyFile & " -o" & Outdir

Robocopy in VBA while using strings

I have a spreadsheet that we run to copy over a list of files/folders based on what we select. In each of these row's we have a few other formula's that with gather other information. What we are trying to do is use robocopy based on a cell's data using strings. Below is currently how we have it setup in VBA, but it does not seem to work.
sSource = Sheets("Sheet1").Range("A2").Value
sFile = Sheets("Sheet1").Range("F2").Value
sPath = Sheets("Sheet2").Range("C2").Value
Shell "cmd /c robocopy sSource sPath sFile"
sSource is a network drive with the full folder path (i.e. \server1\stuff\stuff2\files)
sPath is a local folder on the computer
sFile is just as it sounds, the file name
It appears that it runs successfully, but when I go to the sPath location, there are no files there, just an empty folder.
Your code is very close. You need to concatenate your variables. All that needs to change is the final line to be:
Shell "cmd /c robocopy " & sSource & " " & sPath & " " & sFile
strParms = " /s /xo /mir /zb /R:5 /W:5"
Shell "cmd /c robocopy " & sSource & " " & sPath & sFile & strParms
Replace your code line (Shell "cmd /c robocopy " & sSource & " " & sPath & " " & sFile) with above 2 lines and you'll find files in your destination folder
Actually you're missing "strParms" in your statement which I have added. I have tested and it will definitely work.

Execute .bat file from Excel VBA Macro

Im having a problem with my excel vba macro. I need it to execute a batch file which is in the same folder as the excel workbook. The code works well sometimes. I don't know whats causing the error. Here's the code:
Sub writebatch()
Sheets("code").Select
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:=ThisWorkbook.path & "\code.bat",
FileFormat:=xlTextPrinter, CreateBackup:=False
Application.DisplayAlerts = True
ThisWorkbook.Saved = True
Shell "cmd.exe /k cd " & ThisWorkbook.path & "&&code.bat"
Application.Quit
End Sub
It writes the batch file, but then doesn't execute it. Only once I got the command window to not close and it said the code.bat file could not be found. So the changedir command worked. Is it possible to run cmd.exe and run the code.bat with the relative path without having to changedir?
First of all, when you launch a CMD instance you need to enclose the entire CMD argument if you use any type of operators (&):
CMD /K "command1 & command2"
And then enclose the sub-internal arguments, like this:
CMD /K "command "path with spaces" & command"
So you need to do something like this:
Shell "cmd.exe /k ""cd " & """ & ThisWorkbook.path & """ & " && code.bat"""
Notice I've used """ to escape a quote, but I don't know the way to escape a quote in VBA.
PS: remember to also enclose the code.bat if you have spaces, but ONLY if you have spaces.
I'm pretty sure the problem is down to this line
Shell "cmd.exe /k cd " & ThisWorkbook.path & "&&code.bat"
You need a space in front of the && to separate it from the cd command and after it to separate it from the code.bat.
Shell "cmd.exe /k cd " & ThisWorkbook.path & " && code.bat"
Shell "cmd.exe /k cd /d" & ThisWorkbook.path & "&& code.bat"
here, without /d cmd will open in document folder.
by /d it will open in d drive, you may change this as per your easy.
One way to insert a quote(") into a string is by using the character code conversion function Chr(34), 34 being the ASCII value for quotes(")
I hope it will useful for you.
Dim sfilename, fileName As String
Sub Run_file_bat()
fileName = "" & ThisWorkbook.Path & "\code.bat" & ""
VBA.Shell "Explorer.exe " & fileName, vbNormalFocus
End Sub