Detect PDF file in folder and also check if it is open - pdf

I need codes for below. As I try to find in this website, but nothing match my need. So please if anybody write some codes.
It should search a file in a folder and file name should be taken from cell whatever file name I type for search and if it is open it should warn me that file is open. The file will be in PDF format.
File shall not be duplicate if it find duplicate it shall show me warning REPLACE or NO.
If it is not a duplicate than save as PDF taking whatever name I write in cells and there will 2 different cells.

Option Explicit
Function FileExists(FullFileName As String) As Boolean
FileExists = Len(Dir(FullFileName)) > 0
End Function
Sub SaveAsPDF()
Dim nResult As Long
Dim fName As String
Const fPath As String = "C:\Users\KYD\Desktop\"
With ActiveSheet
fName = .Range("A1").Value & " " & Range("J1").Value & ".pdf"
If Not FileExists(fPath & fName) Then
MsgBox prompt:="PDF file saved." & vbNewLine & "Location <> C:\Users\KYD\Desktop\", _
Buttons:=vbOKOnly + vbInformation, Title:="Thanks"
.ExportAsFixedFormat Type:=xlTypePDF, filename:= _
fPath & fName, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
Else:
nResult = MsgBox(prompt:="PDF file already exit do you want to overwrite a previous file check in below given folder." _
& vbNewLine & "Location <> C:\Users\KYD\Desktop\", Buttons:=vbYesNo + vbCritical, Title:="MME")
If nResult = vbYes Then
.ExportAsFixedFormat Type:=xlTypePDF, filename:= _
fPath & fName, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
End If
Exit Sub
End If
End With
End Sub
i try to write these codes which export pdf and take name from cells and check if the file exited in folder ask user to replace or no.
i need some codes in it which can also check if the file is open taking name from cells. if it is opened show message the file is open else nothing.

Related

VBA code to save PDF does not work properly

I have set up a command button to save the current worksheet as a PDF file. I have played around with this code for several hours and almost got it to work properly but it seems I have disconnected some areas and cannot find my way back. Please see below for the code that I am using and the variables I am having an issue with at this point. Any help or information would be much appreciated! Thanks in advance!
Issues:
When you click 'Cancel' in the save application box, the document still tries to save.
If the file already exists:
Selecting 'Yes' to over-write does not save the document.
Selecting 'No' to over-write and renaming as another already existing document does not prompt another Question box to over-write or not. It simply over-writes the original document name.
Sub PDFFHA()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
strPath = "I:\OCC FRB REMIC Reporting\Quality Control\PDFs"
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
strName = Replace(wsA.Range("D3"), " ", "")
strName = Replace(strName, ".", "_")
strFile = "FHA" & "_" & strName & "_" & "QC" & ".pdf"
strPathFile = strPath & strFile
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If bFileExists(strPathFile) Then
lOver = MsgBox("Overwrite existing file?", _
vbQuestion + vbYesNo, "File Exists")
If lOver <> vbYes Then
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strPathFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created: " _
& vbCrLf _
& strPathFile
Else
GoTo exitHandler
End If
End If
Else
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strPathFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created: " _
& vbCrLf _
& strPathFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
'=============================
Function bFileExists(rsFullPath As String) As Boolean
bFileExists = CBool(Len(Dir$(rsFullPath)) > 0)
End Function
'=============================
With some clean-up and re-formatting.
If the file already exists, you are prompted to overwrite or not. The code only checks for the response to be vbNo since vbYes implies that strPathFile remains the same, i.e. no action needed. The loop handles a Cancel click, as well as the possibility that your new strPathFile is again an existing file.
Option Explicit
Sub PDF_FHA()
Dim wsA As Worksheet: Set wsA = ActiveWorkbook.ActiveSheet
Dim strName, strPath, strFile, strPathFile As String
On Error GoTo errHandler
' Get path
strPath = "I:\OCC FRB REMIC Reporting\Quality Control\PDFs\"
' Get and clean filename
strName = Replace(wsA.Range("D3"), " ", "")
strName = Replace(strName, ".", "_")
strFile = "FHA_" & strName & "_QC.pdf"
strPathFile = strPath & strFile
' Check if file exists, prompt overwrite
If bFileExists(strPathFile) Then
If MsgBox("Overwrite existing file?", _
vbQuestion + vbYesNo, "File Exists") = vbNo Then
Do
strPathFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
' Handle cancel
If strPathFile = "False" Then Exit Sub
' Loop if new filename still exists
Loop While bFileExists(strPathFile)
End If
End If
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strPathFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created: " _
& vbCrLf _
& strPathFile
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
End Sub
'=============================
Function bFileExists(rsFullPath As String) As Boolean
bFileExists = CBool(Len(Dir$(rsFullPath)) > 0)
End Function
'=============================
Firstly, turn Option Explicit on.
Follow the logic in If lOver <> vbYes Then. With the proper indenting you will see that it only handles the <> vbYes path and does not have an Else.
So, you do not actually handle the "Yes" case.
Your "No" logic only brings up a file dialog box and we don't know what you have done to test this (cancel, put new name in, just accept name as presented?). However, there is no additional question on this logic path. If you don't hit "Cancel" to the file dialog it will just save the file.

Replace invalid characters when saving excel as PDF

sorry for the inconvenience. I've tried to google (I always said "google is my friend"), but everything I try only give me an error in VBA.
I would like to add a function, which replace invalid characters (!"#¤%&/()=?`^*>;:#£${[]}|~\,.'¨´+-) in filename with "_".
This is my current (and working) macro:
Sub Save_to_PDF()
Dim v As Variant
Dim name, datedd As String
ThisWorkbook.Sheets(Array("sheet1")).Select
datedd = Date
strFilename = Worksheets("sheet1").Range("B2")
v = Application.GetSaveAsFilename(strFilename & " document " & datedd & " .pdf", "PDF Files (*.pdf), *.pdf")
On Error GoTo openfile
If FileExists(v) Then
Kill v
End If
If VarType(v) = vbString Then
ThisWorkbook.Sheets("sheet1").Activate
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:=v, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, From:=1, To:=1, OpenAfterPublish:=True
End If
Exit Sub
openfile:
MsgBox "You have one file open allready whith that name. Please try again", vbInformation, "Please close file"
Exit Sub
End sub
The following Function will replace pre-selected characters with an alternative:
Function clean_filename(fname As String, replace_with As String)
Dim inv_chars As String
Dim cpos As Long
invchars = "!""#¤%&/()=?`^*>;:#£${[]}|~\,.'¨´+-"
For cpos = 1 To Len(invchars)
fname = Replace(fname, Mid(invchars, cpos, 1), replace_with)
Next
clean_filename = fname
End Function
You could use this by adding v = clean_filename(v,"_") once you've captured v (as a string).
However, you've included . and / in your invalid character list, and both are important to filenames so you may want to consider removing them and/or dealing with those in a different way.

Excel macro - Export to PDF

I have a work book that has many macros to export various worksheets as pdfs in the same location the workbook is saved.
My issue is, if the workbook is saved in a folder on the desktop, then the PDFs are generated just fine.
When the workbook is saved on a network location, the pdfs don't generate. below is a sample of the macro:
Sub PDF_CStmtP()
Application.ScreenUpdating = False
ThisWorkbook.Sheets(Array("C Stmt - P")).Select
pdfname = fileSaveName
ChDir ActiveWorkbook.Path & "\"
fileSaveName = "Closing Statement (Purchase)"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
fileSaveName _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
Application.ScreenUpdating = True
ActiveWorkbook.Sheets("Main Menu").Activate
MsgBox "File Saved " & " " & fileSaveName
End Sub
Your issue is the ChDir command, see here for an explanation: https://www.techonthenet.com/excel/formulas/chdir.php
The important part of this is "The CHDIR statement lets you change the current directory on the current drive. If you need to change drives, try using the CHDRIVE statement first."
When you are trying to save to a network drive you are changing the drive letter from C:\ to whatever the network drive is mapped to, in my case it was U:\ .
The simple fix to your code is to move the Path from ChDir to just being in the filename, so your code should look like:
Sub PDF_CStmtP()
Application.ScreenUpdating = False
ThisWorkbook.Sheets(Array("C Stmt - P")).Select
pdfname = fileSaveName
'ChDir ActiveWorkbook.Path & "\"
fileSaveName = ActiveWorkbook.Path & "\" & "Closing Statement (Purchase)"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= fileSaveName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Application.ScreenUpdating = True
ActiveWorkbook.Sheets("Main Menu").Activate
MsgBox "File Saved " & " " & fileSaveName
End Sub
There are a few other edits you could make to clean it up, but this will solve the issue at hand.
**Based on the comment about the message box, you could change the code to this:
Sub PDF_CStmtP()
Application.ScreenUpdating = False
ThisWorkbook.Sheets(Array("C Stmt - P")).Select
pdfname = "Closing Statement (Purchase)"
'ChDir ActiveWorkbook.Path & "\"
fileSaveName = ActiveWorkbook.Path & "\" & pdfname
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= fileSaveName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Application.ScreenUpdating = True
ActiveWorkbook.Sheets("Main Menu").Activate
MsgBox "File Saved " & " " & pdfname
End Sub

vba failing to export from excel to pdf if the file already exists

Sub printPdf()
Dim strPath As String
Dim myFile As Variant
Dim strFile As String
'On Error GoTo errHandler
Set ws = Application.ActiveSheet
'enter name and select folder for file
' start in current workbook folder
strFile = Replace(Replace(ws.Name, " ", "_"), ".", "_") _
& ".pdf"
strfolder = ThisWorkbook.Path & "\myPdfFiles"
If Len(Dir(strfolder, vbDirectory)) = 0 Then
MkDir (strfolder)
End If
strFile = strfolder & "\" & strFile
ws.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Call closews
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file " & Err & ": " & Error(Err)
Resume exitHandler
End Sub
I am having an issue with saving the pdf files.
If the file already exists in the folder and has some changes made to it the macro will crash with the debugger pointing at the openAfterPulish line and display the following runtime error.
-2214701887(80071779)
"Document not saved."
My goal is that excel should automatically overwrite the old files. Excel will prompt me if I want to overwrite the file when I am saving it manually but crashes when I run the above code.
Check if it exists and delete it. In you VBA IDE go to the tools menu and selecte references. Select "Microsoft scripting runtime"
Dim Response As Integer
Dim fs As FileSystemObject
'We can come back to here after an error.
TryAgain:
If fs.FileExists(strFile) = True Then
On Error Goto DeleteError
fs.DeleteFile(strFile, True)
End If
DeleteError:
Response = MsgBox("Error deleting file. Do you have it open? Try again?", vbYesNo)
' If statement to check if the yes button was selected.
If Response = vbYes Then
Goto TryAgain
Else
Exit sub
End If
On Error Goto 0
ws.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Call closews

VBScript to export selected portion of Excel sheet to a PDF, on one page

I currently have a VBScript that exports an entire excel worksheet to a PDF. I was wondering if it would be possible to set the script to only export the selected areas. I know this can be done manually, but I've been tasked with automating this process. If achieved, it would make the whole reporting proccess a lot easier. The VBScript that I'm currently using is:
Sub PDFActiveSheet()
Dim ws As Worksheet
Dim strPath As String
Dim myFile As Variant
Dim strFile As String
On Error GoTo errHandler
Set ws = ActiveSheet
'enter name and select folder for file
' start in current workbook folder
strFile = Replace(Replace(ws.Name, " ", ""), ".", "_") _
& "_" _
& Format(Now(), "yyyymmdd\_hhmm") _
& ".pdf"
strFile = ThisWorkbook.Path & "\" & strFile
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If myFile <> "False" Then
ws.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF version of report has been created."
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
I've already tried replacing the "Set ws = ActiveSheet" to "Selection", and that has yielded no results. Also, as a side note, when selections are sent to a PDF, they appear on separate sheets.Is it possible to put them both on one sheet?
Thanks in advance for any help that you can offer me.
Try setting the Print Area that you want to output to PDF.