save pdf as cell name with multiple cells - excel

I am trying to save a pdf with the name being info in a cell, but the name involves multiple cells. the cells have formulas inputted because they pull from a seperate sheet in my spreadsheet. how would i could about doing this? this is the formulas in the cells that i want to pull the name for the pdf from:
=VLOOKUP('Work Order'!F26,'Fort McMurray File Services'!A2:AJ1515,6,FALSE)
=VLOOKUP('Work Order'!F26,'Fort McMurray File Services'!A2:AJ1515,6,FALSE)
And this is the code i am using in vba:
Private Sub filename_cellvalue()
'Update 20141112
Dim Path As String
Dim filename As String
Path = "C:\Users\meghan lewis\Desktop\MASS DEMO"
filename = .Range("C7").Value & .Range("D7").Value & _
.Range("E7").Value & .Range("F7").Value & _
.Range("G7").Value & .Range("H7").Value & .Range("I7").Value
ActiveWorkbook.SaveAs filename:=Path & filename & ".PDF", FileFormat:=xlNormal
End Sub
Sub SaveAsPDF()
Dim fName As String
With Worksheets("WORK ORDER")
fName = .Range("C7").Value & .Range("D7").Value & _
.Range("E7").Value & .Range("F7").Value & _
.Range("G7").Value & .Range("H7").Value & _
.Range("I7").Value
End With
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:= _
"C:\Users\meghan lewis\Desktop\MASS DEMO & fName", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End Sub
When I try to save it saves the pdf as mass demo rather than pulling from the cells. Please advise.

How does your code even compile? You have unqualified range addresses like .Range("C7").Value, .Range("D7").Value etc in Sub filename_cellvalue
In Sub SaveAsPDF(), change "C:\Users\meghan lewis\Desktop\MASS DEMO & fName" to "C:\Users\meghan lewis\Desktop\MASS DEMO" & fName
fname within quotes will behave as a String and not a variable.

Related

Modify created macro to print array of sheets instead of Activesheet

I have a Macro that i have managed to put together (its rough, and im new to VBA but it does what i want - for the most part) It currently prints the active sheet to PDF and names it based on cell values. I want to adapt this to print 2 sheets into a single file (if its separate files, thats more than ok!) The cell Value naming bit can be changed at the top which i can do, but its calling for the export to pdf bit that im having an issue with.
I have tried reading up on the Activeworkbook functions but im not having much luck. I have tried calling for a sheet array, but it doesnt like the exportasfixedformat Type:= and im kind of new to that part too. It likes it in the original code, but not when i try and change the ActiveWorkbook.ActiveSheet, it spits it.
It would finalise my calculator :) Any help would be greatly appreciated.
Code:
Sub GetFilePath_Click()
Dim FileAndLocation As Variant
Dim strFilename As String
strFilename = Sheets("Leave Loading").Range("F13") & ", " & Sheets("Leave Loading").Range("F12") & " - " & Sheets("Leave Loading").Range("F14") & "- " & "Leave Loading" & ".pdf"
FileAndLocation = Application.GetSaveAsFilename _
(InitialFileName:=strPathLocation & strFilename, _
filefilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select a Location to Save")
ActiveWorkbook.ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFilename, OpenAfterPublish:=True
End Sub
Thank you in advance!
Option Explicit
Sub GetFilePath_Click()
Dim FileAndLocation As Variant
Dim strFilename As String, strPathLocation As String
strPathLocation = ""
With Sheets("Leave Loading")
strFilename = .Range("F13") & ", " & .Range("F12") & " - " _
& .Range("F14") & "- Leave Loading" & ".pdf"
End With
FileAndLocation = Application.GetSaveAsFilename _
(InitialFileName:=strPathLocation & strFilename, _
filefilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select a Location to Save")
Sheets(Array("Sheet2", "Sheet4")).Select
Sheets("Sheet2").Activate
ActiveWorkbook.ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFilename, OpenAfterPublish:=True
End Sub

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.

How to add month to an export macro name?

i have an macro that exports worksheets to pdf's to a designated folder using their sheet name. What I would like is to add the month in as part of the filename. I can retrieve this from a cell in my workbook. Where in my code would I add this reference to?
Dim outFldr As String
Dim ws As Worksheet
Dim i As Variant, sheets_to_select As Variant
outFldr = ActiveWorkbook.Path
sheets_to_select = Array("Summary", "PLC", "MI", "Venture", "EIS", "VCT", "PE", "Debt")
For Each i In sheets_to_select
ThisWorkbook.Sheets(i).ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=outFldr & "\" & i & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Next i
MsgBox ("All pdf's exported.")
End Sub
Read the date from Excel, use for example format to get the month number or name and add that to the file name. I prefer to use intermediate variables as this makes the code much easier to read and debug.
Adapt the format to create the pattern you want - you could also include the year.
For Each i In sheets_to_select
Dim filename As String, filedate As Date, month As String
filedate = ThisWorkbook.Sheets(1).Range("A1") ' Change this so that it reads your cell with the date
month = Format(filedate, "mm") ' For month as 2-digits
month = Format(filedate, "mmm") ' For month as 3 letters month name
month = Format(filedate, "mmmm") ' For month as full month name
filename = outFldr & "\" & i & "_" & month & "_.pdf"
ThisWorkbook.Sheets(i).ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Next i

Run Time Error 5 - when saving to shared drive

My code runs perfectly when I save to my local drive, but when I save to the shared drive I get Runtime Error 5? How is this occurring?
I have unmerged cells and put it as center across selection
Ensured that the whole document is within the print margins
Edit: I have tried saving into the folder directory above where I was saving and it works. I understand that there is a character limit (pathname and title), which might be the problem? Is there a way to solve this?
The error is in the following area:
'Creating Only the PDF based on Company Network - there is an existing folder
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=Fldr & "\" & Title & ".pdf", _
Quality:=xlQualityStandard, _
IgnorePrintAreas:=False
This is the whole code:
Option Explicit
Private Function selectfolder()
'Defining the Variables
Dim user_name As String
user_name = Environ("username") 'to pick up the username from work environment
'Prompt for folder creation
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select the folder to save"
.InitialFileName = "C:\Users\" & user_name & "\Department\"
.AllowMultiSelect = False
If .Show <> -1 Then Exit Function 'if user does not press OK, end the function'
selectfolder = .SelectedItems(1)
End With
End Function
Sub SaveActiveSheetAsPDF()
'Create a message box to ask user before proceeding
If MsgBox("This will print to PDFs. Continue?", vbYesNo + vbQuestion + vbDefaultButton2, "Printing to PDFs") = vbNo Then Exit Sub
'Defining the Type of Variables
Dim inputrange As Range 'Range represents a cell or multiple cells in Excel
Dim cell As Range
Dim network, Address, Fldr, Title As String
'If user does not choose a folder
Address = selectfolder
If Address = "" Then
Exit Sub
End If
'Determine (set) where validation comes from - create a reference point
Set inputrange = Evaluate(Range("G2").Validation.Formula1)
For Each cell In inputrange
Range("G2").Value = cell.Value
'Defining the Company Network Folder variables
network = Range("C6").Value
Fldr = Address & "\" & network
Title = "MonthlyReport (" & Format(Range("C8"), "mmmm") & ") - " & ActiveSheet.Range("B2").Value & " (" & ActiveSheet.Range("G2").Value & ")"
'Creating the folder based on Company Network - No existing folder
If Dir(Fldr, vbDirectory) = "" Then
'Create a folder
MkDir Fldr
'Save Active Sheet as PDF and to Company Network file
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=Fldr & "\" & Title & ".pdf", _
Quality:=xlQualityStandard, _
IgnorePrintAreas:=False
'Creating Only the PDF based on Company Network - there is an existing folder
Else
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=Fldr & "\" & Title & ".pdf", _
Quality:=xlQualityStandard, _
IgnorePrintAreas:=False
End If
Next cell
'Create a message box at end of task to inform user it is complete
MsgBox "Generation of PDF Reports and Folders Completed", vbInformation, "Complete"
End Sub
It is difficult to diagnose problems with network drive without more information, but I could suggest a workaround instead.
You could save the file on your local drive and then move it using the File System Object in VBA. Here's how it would look like:
'Save Active Sheet as PDF in temporary folder
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=Environ("TEMP") & "\" & Title & ".pdf", _
Quality:=xlQualityStandard, _
IgnorePrintAreas:=False
'Move PDF to Company network drive
Dim fso As FileSystemObject
Set fso = New FileSystemObject
fso.MoveFile Environ("TEMP") & "\" & Title & ".pdf", Fldr & "\" & Title & ".pdf"
Note that for this code to work, you need a reference to the Microsoft Scripting Runtime Library.

create hyperlink in visual basic excel between worksheets

When I used this formula,
Sub IndexingSheets()
Sheets(1).Range("B3").Formula = _
"=HYPERLINK(""#" & ThisWorkbook.Sheets(2).Name & "!A5"", ""TextToDisplay"")"
Sheets(2).Range("A5").Formula = _
"=HYPERLINK(""#" & ThisWorkbook.Sheets(1).Name & "!B3"", ""TextToDisplay"")"
End Sub
it creates a hyperlink but when I click it, it shows reference is not valid. Then when I changed the formula in the formula bar, I added the filename and it worked so it will now look like this:
=HYPERLINK("[Book1.xls]'Sheet2 123!A5", "gg")
But originally it is just like this:
=HYPERLINK("#Sheet2 123!G20", "gg")
How can I alter my original code which I shown on the topmost so that this:
=HYPERLINK("[Book1.xls]'Sheet2 123!A5", "gg")
will be shown or will be the format in the formula bar? my problem is how can i put the filename now without just copying the filename itself and not just pasting it in the code?
I just want to clarify that there's a messagebox that says you should input the 2nd name of the sheet. so the name of the sheet is not just "Sheet2" anymore.
For instance you put in the msgbox "123", the name of the sheet would now become "Sheet2 123". the messagebox is already present, no need to create a code for it.
Try this. You need to put single-quotes around the sheet names, to account for the possible spaces in sheet names. If you omit single-quotes, then the sheet names must not contain any spaces.
Sub IndexingSheets()
With ThisWorkbook
.Sheets(1).Range("B3").Formula = _
"=HYPERLINK(""#'" & .Sheets(2).Name & "'!A5"", ""Jump to Sheet2!A5"")"
.Sheets(2).Range("A5").Formula = _
"=HYPERLINK(""#'" & .Sheets(1).Name & "'!B3"", ""Jump to Sheet1!B3"")"
End With
End Sub
To include the Workbook name (not necessary, I don't think):
Sub IndexingSheets()
With ThisWorkbook
.Sheets(1).Range("B3").Formula = _
"=HYPERLINK(""#'[" & .Name & "]" & .Sheets(2).Name & "'!A5"", _
""Jump to Sheet2!A5"")"
.Sheets(2).Range("A5").Formula = _
"=HYPERLINK(""#'[" & .Name & "]" & .Sheets(1).Name & "'!B3"", _
""Jump to Sheet1!B3"")"
End With
End Sub
And, an alternate method of achieving the same -- this one includes the Workbook name, too:
Sub IndexingSheetsWithFileName()
With ThisWorkbook
.Sheets(1).Hyperlinks.Add Anchor:=.Sheets(1).Range("B3"), _
Address:="", SubAddress:= _
"'[" & .Name & "]" & .Sheets(2).Name & "'!A5", _
TextToDisplay:="Jump to Sheet2!A5"
.Sheets(2).Hyperlinks.Add Anchor:=.Sheets(2).Range("A5"), _
Address:="", SubAddress:= _
"'[" & .Name & "]" & .Sheets(1).Name & "'!B3", _
TextToDisplay:="Jump to Sheet1!B3"
End With
End Sub

Resources