Replace invalid characters when saving excel as PDF - vba

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.

Related

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

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.

BeforePrint Event is Firing without Printing

I have the code below. It makes me wonder why the BeforePrint event in the workbook codes is fired even though I am not printing anything. The workbook definitely is not blank. The error is in the creation of the PDF file.
The file does a simple job of saving the worksheet in a PDF format with the name of the sheet, the file path of the workbook, and some details inside the worksheet.
Anything that I am missing? I am not new to VBA but this bugs me a lot today. I am using MS Excel 2016 on Windows 7 ultimate.
Edit: I tried removing the following codes below but the problem still persists:
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
The code is as follows:
Option Explicit
Public Sub createpdffile()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Dim sheetname As String, sheetcode As String
Dim iRow As Long
Dim openPos As Integer
Dim closePos As Integer
'temporarily disable error handler so that I can see where the bug is.
'On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
wbA.Save
'get last row of sheet and set print area to last row with L column
iRow = wsA.Cells(Rows.Count, 1).End(xlUp).Row
wsA.PageSetup.PrintArea = wsA.Range("A1:L" & iRow).Address
'just checking name in sheet and removing needed characters
sheetname = wsA.Name
openPos = InStr(sheetname, "(")
closePos = InStr(sheetname, ")")
sheetcode = Mid(sheetname, openPos + 1, closePos - openPos - 1)
'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
'create default name for saving file
strFile = sheetcode & " No. " & wsA.Cells(11, 9) & " - " & wsA.Cells(8, 3) & ".pdf"
strPathFile = strPath & strFile
'use can enter name and
' select folder for file
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
'export to PDF if a folder was selected
'THIS IS WHERE THE ERROR IS LOCATED
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
'confirmation message with file info
MsgBox "PDF file has been created: " _
& vbCrLf _
& myFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file" & vbNewLine & _
"Please complete the details needed!", vbOKOnly + vbExclamation, "Error Saving as PDF"
Resume exitHandler
End Sub
Solution from Foxfire and Burns and Burns' idea:
I added a public declaration before the main sub.
Option Explicit
'added line
Public myboolean as Boolean
Public Sub createpdffile()
myboolean = True
....
Then I added a line in the BeforePrint Event that says:
If myboolean = True Then Exit Sub
This now bypasses the BeforePrint event when the virtual PDF printer is called.
wsA.ExportAsFixedFormat
That line activates the BeforePrint Event. Actually, you are printing a PDF file. It works as a virtual PDF Printer.

Excel Macro which saves a worksheet

I'm totally new to Microsoft VBA and I'm getting trouble to fix an Excel macro.
The intention of this macro is that, when pressing a button, it automatically saves the active worksheet on a file but it is not working and I don't know why.
It seems correct to me.
Sub Save()
'
' Save Macro
'
Sheets("My_sheet").Select
ChDir "C:\my_file"
ActiveWorkbook.SaveAs Filename:=Range("B6"), FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, _
CreateBackup:=False
Sheets("My_sheet").Select
'
End Sub
it seems to work fine as long as the sheet name is set as "My_Sheet", folder exist and file name is correct.
You can try this to check if they are OK before saving:
Sub SaveMe()
Dim filename As String
'check if directory exist
If Dir("C:\my_file", vbDirectory) = "" Then
'if not ask if it should be created and continued
rspCreate = MsgBox("Directory doesn't exist, do you wish to create it and continue?", vbYesNo)
If rspCreate = vbYes Then
'create dir and carry on
MkDir "C:\my_file"
ElseIf rspCreate = vbNo Then
'no selected, stop execution
Exit Sub
End If
End If
filename = Range("B6")
Sheets("My_sheet").Select
ChDir "C:\my_file"
'check if file name is valid
If FileNameValid(filename) Then
ActiveWorkbook.SaveAs filename:=Range("B6"), FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, _
CreateBackup:=False
Else
MsgBox "Invalid file name, file not saved"
End If
Sheets("My_sheet").Select
End Sub
'check if vali file name is used in cell
Function FileNameValid(sFileName As String) As Boolean
Dim notAllowed As Variant
Dim i As Long
Dim result As Boolean
'list of forbidden characters
notAllowed = Array("/", "\", ":", "*", "?", "< ", ">", "|", """")
'Initial result = OK
result = True
For i = LBound(notAllowed) To UBound(notAllowed)
If InStr(1, sFileName, notAllowed(i)) > 0 Then
'forbidden character used
result = False
Exit Function
End If
Next i
FileNameValid = result
End Function

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.