Define file name via macro - excel

I have the following piece of code to save a pdf file from an existing excel file.
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = ThisWorkbook.FullName
If FSO.FileExists(s(0)) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), ".pdf")
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF,_
_ Filename:=sNewFilePath, Quality:=xlQualityStandard,_
_ IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
Since the code has to be run recursively, I'd would like add to the file name the week number, contained in a given cell (B2) in the sheet.
I tried replacing
s(0) = ThisWorkbook.FullName & Cells(2,2)
but it is not working. Where is the error?

FullName property returns the full path & filename & extension. Appending Cells(2,2) to that will give you a value like "c:\path\to\filename.xlsx" & Cells(2,2).Value.
You need to insert the week number (Cells(2,2)) before the file extension part.
You can probably do that like so:
sNewFilePath = Replace(s(0), s(1), Cells(2,2).Value & ".pdf")
Or, without using FileSystemObject:
Dim fullName As String, weekNum As String
Dim sNewFilePath As String
weekNum = Cells(2,2).Value
fullName = ThisWorkbook.FullName
'If the file exists, the `Dir` function will return the filename, len != 0
If Len(Dir(fullName)) <> 0 Then
'remove the extension using Mid/InstrRev functions, _
build the new filename with weeknumber & pdf extension
sNewFilePath = Mid(fullName, 1, InstrRev(fullName,".")-1) & weekNum & ".pdf"
'Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF,_
_ Filename:=sNewFilePath, Quality:=xlQualityStandard,_
_ IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If

FullName includes the file extension. Perhaps this (you would be better off adding a sheet reference to B2 also).
s(0)=split(ThisWorkbook.FullName, ".")(0) & Cells(2, 2) & ".pdf"

Something like this would do it (I cleaned it up a little bit):
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Sub SavePDF()
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = ThisWorkbook.FullName
If FSO.FileExists(s(0)) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Left(s(0), InStrRev(s(0), "\")) & ".pdf"
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
sNewFilePath & Sheets("wsTakeOff").Range("AY2").Value & " - " & Sheets("wsTakeOff").Range("D1") & ".pdf", Quality:= _
xlQualityStandard, includedocproperties:=False, ignoreprintareas:=False, _
openafterpublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
End Sub

Related

VBA Excel - Export PDF file from Excel with second page

Just want to ask if how can I export a PDF file with vba? The thing is I do have a 10-F and 10-B sheet. The code below is working in the 10-F sheet. My problem is how can I export the data in the 10-B sheet together with the 10-F? The first page is the data in 10-F while the data in 10-B will be on the second page.
The range for the 10-B sheet is "B10:AD92".
Sub Ver_PDF()
'Create and assign variables
Dim saveLocation As String
Dim rng As Range
lname = ThisWorkbook.Sheets("HOME").Range("K12")
fname = ThisWorkbook.Sheets("HOME").Range("K13")
Name = fname & " " & lname
pdfile = "V-" & Name & ".pdf"
saveLocation = ThisWorkbook.Path & "\V-PDF\" & pdfile
Set rng = Sheets("10-F").Range("B9:AD89")
Dim strFileExists As String
strFileExists = Dir(saveLocation)
If strFileExists <> "" Then
Dim Ret
'~~> Change this to the relevant file path and name
Ret = IsFileOpen(saveLocation)
If Ret = True Then
MsgBox "Please close the PDF file before proceeding...", vbCritical + vbOKOnly, "Error"
Exit Sub
End If
End If
rng.ExportAsFixedFormat Type:=xlTypePDF, _
FileName:=saveLocation, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Any help is highly appreciated! Thanks!
This code will do what you want. Change the worksheet names in the array as well as the destination path and file name.
Sub ExportAsPDF()
Dim FolderPath As String
Dim FileName As String
FolderPath = "D:\Test PDFs\" ' change to suit: end on back-slash
FileName = "Test" ' change to suit
On Error Resume Next
MkDir FolderPath
On Error GoTo 0
Worksheets(Array("10-F", "10-B")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
FileName:=FolderPath & FileName & ".PDF", _
OpenAfterPublish:=True, _
IgnorePrintAreas:=False
MsgBox "PDF was successfully created."
Worksheets(1).Select
End Sub
Change OpenAfterPublish to False if you don't want to see the result right away.

Excel VBA Print w Automated File Name and Location using Range.ExportAsFixedFormat

https://www.contextures.com/excelvbapdf.html
The following is perfect, but it prints the entire sheet.
full thread
Sub PDFActiveSheet()
'www.contextures.com
'for Excel 2010 and later
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
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
strTime = Format(Now(), "yyyymmdd\_hhmm")
'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
'replace spaces and periods in sheet name
strName = Replace(wsA.Name, " ", "")
strName = Replace(strName, ".", "_")
'create default name for savng file
strFile = strName & "_" & strTime & ".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
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'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"
Resume exitHandler
End Sub
but I'm having trouble with this
'export to PDF if a folder was selected
If myFile <> "False" Then
` wsA.ExportAsFixedFormat
Type:=xlTypePDF,
Filename:=myFile,
Quality:=xlQualityStandard,
IncludeDocProperties:=True,
IgnorePrintAreas:=False,
OpenAfterPublish:=False`
The only thing I'm trying to accomplish is print a range (Preferably named) in lieu of the entire sheet. I created dims and set a range to use in lieu of the 'wsA' Sheet and it is bugging.
Dim rnG As Range
Set rnG = Range("Y1:AG46")
rnG.ExportAsFixedFormat _
Are the only lines that I've added. It'll work as I want it, but intermittently and I've got no idea why. It bugs in yellow the entire ExportFileAsFixedFormat subtext and points to not recognizing the specified Range.
I suspect this is because you are not qualifying the range. Try
Set rnG = wsA.Range("Y1:AG46")
Without qualification works correctly only if wsA is the active sheet.

Changing Date format when saving as PDF

I'm confronted with the following issue:
I would like to save a Sheet to PDF using VBA. The file name should include the values of some Cells, including one cell that holds a date. This date has been changed to the format "dd-mm-yyyy" (by means of code or in the Number Format dropdown in the Home tab) since Filenames cannot hold "/" but when I look at the formula bar the date is still "dd/mm/yyyy".
When running the code the filename returns the date in that format...
How can I change the date format so that I can include it correctly in the filename?
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strDate As Range
Dim strName As Range
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 = ActiveWorkbook.Sheets("Devis")
Set strName = ActiveWorkbook.Sheets("Calc").Range("Designation")
Set strDate = ActiveWorkbook.Sheets("Calc").Range("arrival")
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
strDate = Replace(strDate, "/", "-")
strFile = strName & "_" & strDate & ".pdf"
strPathFile = strPath & strFile
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:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'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"
Resume exitHandler
End Sub
You will see I tried to replace the "/" with "-" in the code but this does not seem to help...
Looking forward to your suggestions!
When you use strDate = Replace(strDate, "/", "-") you are calling the value in cell. Even if you see a date on it, dates on Excel are, actually, numbers.
So Replace(strDate, "/", "-") does not work, because there is nothing to replace.
Using Format allows to change how a value is displayed, and you can save that new formated value into a string variable.
That explains why strFile = strName & "_" & Format(strDate,"dd-mm-yyyy") & ".pdf" works.

Problem with VBA print to pdf error code in windows 10 environment

I have code which works fine in windows 7 and other windows version environments, but when some of the users have been upgraded to Windows 10 (myself included)
This is a macro enabled sheet which has worked fine for 3 years, and as far as I can tell the only change is the 'upgrade' to windows 10!
this is the bit of code which seems to fail:
'saveas function for pdf
ws.range("A1:K69").ExportAsFixedFormat Type:=xlTypePDf, _
filename:=path & fname, _
Quality:-xlqualityStandard, _
IncludeDocProperties:=True' _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
I get a Run-Time error Method 'ExportAsFixedFormat' of Object 'Range' failed. But when someone in an earlier windows environment runs the code it works perfectly and I get the pdf created, saved and opened for the user to insert other documents into.
Driving me mental, and I cannot work out why this would fail - and also sporadically as well.
I use the below to auto save an excel sheet as PDF, should try and save it to the excel file location and name it after the tab name.
If you set a print area on the sheet for the range you want to view in the PDF first, it should work :)
Hope it helps
Sub Export_Summary()
'
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
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
strTime = Format(Now(), "yyyymmdd\_hhmm")
'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
'replace spaces and periods in sheet name
strName = Replace(wsA.Name, " ", "")
strName = Replace(strName, ".", "_")
'create default name for savng file
strFile = strName & "_" & strTime & ".pdf"
strPathFile = strPath & strFile
'user 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
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'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"
Resume exitHandler
End Sub

Exporting excel worksheet to CSV via VBA with formula results shown

I have an excel workbook with multiple sheets, i'm trying to export a particular sheet as a CSV file and save it to the users desktop without impacting the original. Everything seems to work, however the file is coming out as a PDF, any ideas? Code is below:
Sub CSVSagePricelist_Click()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim TempWB As Workbook
Dim strTime As String
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 = Sheet8
strTime = Format(Now(), "yyyymmdd\_hhmm")
'get active workbook folder, if saved
strPath = CreateObject("WScript.Shell").specialfolders("Desktop")
If strPath = "" Then
strPath = CreateObject("WScript.Shell").specialfolders("Desktop")
End If
strPath = strPath & "\"
'replace spaces and periods in sheet name
strName = Replace(wsA.Name, " ", "")
strName = Replace(strName, ".", "_")
'create default name for saving file
strFile = "INT-ONLY-SAGE-PRICELIST" & "_" & Sheet16.Range("C17").Text & "_" & Sheet16.Range("B2").Text & ".csv"
strPathFile = strPath & strFile
'use can enter name and
'select folder for file
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="CSV (Comma delimited) (*.csv), *.csv", _
Title:="Select Folder and FileName to save")
'export to PDF if a folder was selected
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlCSV, _
Filename:=myFile
'confirmation message with file info
MsgBox "Sage pricebook CSV created: " _
& vbCrLf _
& myFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create CSV file"
Resume exitHandler
End Sub
Thanks,
Nick
Following code lines / code blocks are needed to corrected. Also you should include Option Explicit in the beginning of code so that undeclared variables are easily identified.
A.)
Set wsA = Sheet8
Will give Compiler error. Variable not defined. It should be changed to
Set wsA = Sheets("Sheet8")
Similarly
strFile = "INT-ONLY-SAGE-PRICELIST" & "_" & Sheet16.Range("C17").Text & "_" & Sheet16.Range("B2").Text & ".csv"
strPathFile = strPath & strFile
It should be changed to
strFile = "INT-ONLY-SAGE-PRICELIST" & "_" & Sheets("Sheet16").Range("C17").Text & "_" & Sheets("Sheet16").Range("B2").Text & ".csv"
strPathFile = strPath & strFile
B.) Block of code for saving as pdf file has incorrect syntax.
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlCSV, _
Filename:=myFile
'confirmation message with file info
MsgBox "Sage pricebook CSV created: " _
& vbCrLf _
& myFile
End If
Needs to be Changed to
'export to PDF if a folder was selected
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
& vbCrLf _
& myFile
End If
With these changes your final code should work fine.
Option Explicit
Sub CSVSagePricelist_Click()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim TempWB As Workbook
Dim strTime As String
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 = Sheets("Sheet8")
strTime = Format(Now(), "yyyymmdd\_hhmm")
'get active workbook folder, if saved
strPath = CreateObject("WScript.Shell").specialfolders("Desktop")
If strPath = "" Then
strPath = CreateObject("WScript.Shell").specialfolders("Desktop")
End If
strPath = strPath & "\"
'replace spaces and periods in sheet name
strName = Replace(wsA.Name, " ", "")
strName = Replace(strName, ".", "_")
'create default name for saving file
strFile = "INT-ONLY-SAGE-PRICELIST" & "_" & Sheets("Sheet16").Range("C17").Text & "_" & Sheets("Sheet16").Range("B2").Text & ".csv"
strPathFile = strPath & strFile
'use can enter name and
'select folder for file
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="CSV (Comma delimited) (*.csv), *.csv", _
Title:="Select Folder and FileName to save")
'export to PDF if a folder was selected
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
& vbCrLf _
& myFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create CSV file"
Resume exitHandler
End Sub

Resources