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

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

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

File is not saving to newly made folder in VBA

I have a macro that created a folder by data within a pathway, and I want a cut of a manager roster to be saved in that folder. Since the folder name varies, this needs to be dynamic.
I want it to go something like this:
Dim sPath As String
sPath = "M:\mgr1_TCR_Reports\"
If Len(Dir(sPath & "_" & Format(Date, "mm_dd_yyyy"), vbDirectory)) = 0 Then
MkDir (sPath & "_" & Format(Date, "mm_dd_yyyy"))
End If
End Sub
and saving this like:
.SaveAs Filename:="M:\mgr1_TCR_Reports\" & "_" & Format(Date, "mm_dd_yyyy_") & "\" & Manager, FileFormat:=xlOpenXMLWorkbook, Password:=""
.Close
But I keep getting a runtime 1004: document not saved on ^^^ the second line of code I provided.
Any idea what's going on?

Why is a just created file not found?

I have
error 53 'file not found'
Here is the most streamlined version of the script:
Sub Test()
Dim NJ As String, path As String, Oud As String, Archief As String, Nieuw As String
path = "C:\Test" & "\"
Oud = path & "A"
Archief = path & ("Archive") & "\" & "A"
Nieuw = path & "B"
Application.Workbooks.Add
ActiveWorkbook.SaveAs Oud
ActiveWorkbook.SaveAs Archief
ActiveWorkbook.SaveAs Nieuw
Kill Oud
End Sub
I tried to bypass the possibility of a too-long pathname by limiting it to its bare essentials.
I created a new file, which I gave a variable name to make sure no mistakes were made in the pathname.
I spoke with IT to make sure I have proper permissions to change, edit and delete files.
The script does not make a lot of sense, (why not just create Archief and Nieuw?), but I am trying to understand the error that occurs in another script in which I try to archive some files (say, "name 2017") in an archive folder, rename them for the new year in the original file (e.g. "name 2018") and then kill the original 2017 files to clean up the mess.
It does not make sense that the file I just created cannot be found.
Please do the below changes:
1) add these lines to your Code:
Dim filename As String
filename = "test.xls" 'You can select any name and any excel file format
2) Replace these lines:
Application.Workbooks.Add
ActiveWorkbook.SaveAs Oud
ActiveWorkbook.SaveAs Archief
ActiveWorkbook.SaveAs Nieuw
Kill Oud
With these:
ActiveWorkbook.SaveAs Oud & "\" & filename
ActiveWorkbook.SaveAs Archief & "\" & filename
ActiveWorkbook.SaveAs Nieuw & "\" & filename
Kill Oud & "\" & filename

Automating usage MS Word as PDF to HTML converter [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a task to convert several hundred PDF documents to HTML format. I have tried multiple standalone converters, but they have problems with handling columns and hyphen justification.
However, if I just open a document in MS Word, it handles them perfectly.
So, basically, I need a way to automate opening PDF in Word, waiting for it to process and saving it as HTML (filtered).
Does somebody knows, how can I do it?
We can do it in PowerShell.
Break your requirement in two pieces
FIRST - Convert PDF to WORD Document
'**** The script runs in a loop until it detects a new file in the directory
'**** It checks the source folder every 30 seconds. To change this interval
'**** change the sleep time at the end of the program to the number of seconds x 1000
'**** wscript.sleep (15000) would check the folder every 15 seconds
'****
'****
'**** The program uses AnyBizSoft PDtoWord converter. It is available as a free version off of
'*** facebook here - Facebook - http://www.facebook.com/AnyBizSoft?v=app_6009294086
'*** You can buy it from thier website at http://www.anypdftools.com/pdf-to-word.html
'*** I have no connection with them other than they were the first one i found that worked with
'*** a command line.
'***
'*** The script uses two directories. C:\Source\ is where pdf files are copied to
'*** C:\Converted is where the converted file is placed. It is either a doc file if you have Office 2003 or
'*** older or a docx if you have Office 2007 or newer.
'*** After the file is converted the original pdf is deleted. This can be changed by commenting out the
'*** Line that deletes the file near the end of the script.
'***
'*** The script can be placed anywhere, but the pdftoword folder needs to be copied from the program files
'*** directory to the c:\source folder
'***
'Option Explicit
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim strComputer
strComputer = "."
spath="C:\source\" '*** Source directory
dpath="C:\converted\" '*** Destination or Converted Directory
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " _
& "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _
& "TargetInstance.GroupComponent= " _
& "'Win32_Directory.Name=""c:\\\\source""'")
Do
Do
set sourcefolder=objFso.GetFolder(spath)
numfiles=sourcefolder.files.count
set sourcefiles = sourcefolder.files
for each objFile in sourcefiles
sourcefile = objFile.name
next
loop until (numfiles > 0)
'*** Call pdftoword to convert the file
Set wshShell = WScript.CreateObject ("WSCript.shell")
convertstr="c:\source\pdftoword\pdftoword.exe " & chr(34) & spath & sourcefile & chr(34)
wshshell.run convertstr, 6, false
Do '*** Wait for docx to be created before continuing
Set objLatestEvent = colMonitoredEvents.NextEvent
loop until (instr(objLatestEvent.TargetInstance.PartComponent,"doc") > 0)
'*** Make time stamp for file name
d = Now
hhmmss = Right("00" & Hour(d), 2) & Right("00" & Minute(d), 2) & Right("00" & Second(d), 2)
'*** Get just the filename without the extension
sourcefilename = left(sourcefile,instr(sourcefile,".")-1)
'*** Add the timestamp to the converted file
newname = sourcefilename & "-" & hhmmss
'*** Exit program if file exists in the destination folder. Highly unlikely since it is timestamped
if objfso.FileExists(dpath & newname & ".docx") then
wscript.echo "Destination file " & dpath & newname & ".docx exists already"
WScript.Quit
end if
if objfso.FileExists("c:\converted\" & newname & ".doc") then
wscript.echo "Destination file " & dpath & newname & ".doc exists already"
WScript.Quit
end if
'*** move converted file to the converted folder then delete original
if objfso.FileExists(spath & sourcefilename & ".docx") then
newname= dpath & newname & ".docx"
oldname = spath & sourcefilename & ".docx"
objfso.Movefile "" & oldname & "", "" & newname & ""
objfso.DeleteFile("" & spath & sourcefile & "") 'Delete or comment this line if you do not want the original deleted
end if
if objfso.FileExists(spath & sourcefilename & ".doc") then
newname= dpath & newname & ".doc"
oldname = spath & sourcefilename & ".doc"
objfso.Movefile "" & oldname & "", "" & newname & ""
objfso.DeleteFile("" & spath & sourcefile & "") 'Delete or comment this line if you do not want the original deleted
end if
' *** Kill PDFtoword process
strProcessKill="PDFtoWord.exe"
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'PDFtoWord.exe'" )
For Each objProcess in colProcess
objProcess.Terminate()
Next
wscript.sleep (30000) 'Wait 30 seconds to look for next file. 1000 = 1 second
Loop
SECOND - Convert WORD Documents TO HTML
param([string]$docpath,[string]$htmlpath = $docpath)
$srcfiles = Get-ChildItem $docPath -filter "*.doc"
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatFilteredHTML");
$word = new-object -comobject word.application
$word.Visible = $False
function saveas-filteredhtml
{
$opendoc = $word.documents.open($doc.FullName);
$opendoc.saveas([ref]"$htmlpath\$doc.fullname.html", [ref]$saveFormat);
$opendoc.close();
}
ForEach ($doc in $srcfiles)
{
Write-Host "Processing :" $doc.FullName
saveas-filteredhtml
$doc = $null
}
$word.quit();
Save this code to convertdoc-tohtml.ps1 and you can run it on a set of word documents regardless of doc or docx extension.
Here’s how you can run it:
convertdoc-tohtml.ps1 -docpath "C:\Documents" -htmlpath "C:\Output"

Excel 2010 VBA: Save file using value from cell to determine path and filename

I am trying to write some code that will save several tabs as a pdf document in folder specified by files within excell. I would like for cells within the document to dictate where this file is saved. I am not sure if this is possibly, but if it is any help would be good! I am currently getting a Run-time error '1004' during the save process of my code.
And yes, I do have the folders created that are being referenced.
Sub asdf()
Dim Fname As String
Dim Fpath As String
Dim YrMth As String
Fname = Sheets("Sheet1").Range("A1").Text
YrMth = Sheets("Sheet1").Range("A2").Text & "\" & Sheets("Sheet1").Range("A3").Text
Fpath = "C:\Documents and Settings\My Documents\" & YrMth & "\Group\" & Fname & ".pdf"
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet4")).Select
Application.DisplayAlerts = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=Fpath, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End Sub
Your code works for me, but not with the path you've specified.
Declare a new string variable:
dim myDocsPath as String
Get the path using:
myDocsPath = Environ$("USERPROFILE") & "\My Documents\"
and then change your definition for Fpath to:
Fpath = myDocsPath & YrMth & "\Group\" & Fname & ".pdf"
If I change the end of myDocsPath to & "\My foo Documents\" I get the same 1004 error you are getting.
Try replace line in your code
Fpath = "C:\Documents and Settings\My Documents\" & YrMth & "\Group\" & Fname & ".pdf"
with
Dim WshShell As Object
Dim MyDocsFolder As String
Set WshShell = CreateObject("WScript.Shell")
MyDocsFolder = WshShell.SpecialFolders("MyDocuments") & "\"
Fpath = MyDocsFolder & YrMth & "\Group\" & Fname & ".pdf"
Edit:
The core of this solution is in line:
MyDocsFolder = WshShell.SpecialFolders("MyDocuments") & "\"
which returns system path to My Documents, irrespectively from local system settings like language or nonstandard location of My Documents folders. Then it adds a backslash at the end.
It is more elegant (and the code becomes more portable) if you ask system about special folders than hardcode such data in your script.
More on Windows special folders in VBA you can find https://www.rondebruin.nl/win/s3/win027.htm