VBA - 1 page setup different than rest (unknown #) pages - excel

I am trying to do page setup on multiple sheets with same range. However, one of the sheets "Dashboard" has different page set up range. It is going to be "D24:K73" How can I accomplish that with the code below? I have tried modifying it but my skills do not produce wanted results.
Sub Octsaveaspdf()
Dim ws As Worksheet
Dim FileName As String
Dim FilePath As String
For Each ws In Sheets
If ws.Visible Then ws.Select (False)
Next
FilePath = Range("Instructions!B16").Value
FileName = Range("Dashboard!Q26").Text
Range("$p24:$w73").Select
Application.PrintCommunication = False
With ActiveSheet.PageSetup
LeftMargin = Application.CentimetersToPoints(0.1)
.RightMargin = Application.CentimetersToPoints(0.1)
.FitToPagesWide = 1
End With
Application.PrintCommunication = True
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, FileName:=FilePath & "Compare " & FileName & ".pdf" _
, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End Sub
I truly appreciate all the help :) Thank you!

Move your export into a separate procedure and call it multiple times with different ranges to export.
The code below will work through each visible sheet and export different ranges depending on the sheet name.
Each export will be given the same name, so you'll need to do something about that to stop problems with file name conflicts.
Private FilePath As String
Private FileName As String
Public Sub OctSaveAsPDF()
Dim ws As Worksheet
FilePath = ThisWorkbook.Worksheets("Instructions").Range("B16")
FileName = ThisWorkbook.Worksheets("Dashboard").Range("Q26")
For Each ws In ThisWorkbook.Worksheets
If ws.Visible Then
Select Case ws.Name
Case "Dashboard"
PerformExport ws.Range("D24:K73")
Case "Sheet1", "Sheet2"
PerformExport ws.Range("A1:Z10")
Case Else
PerformExport ws.Range("P24:W73")
End Select
End If
Next ws
End Sub
Public Sub PerformExport(xpRng As Range)
With xpRng
With .Parent.PageSetup 'The parent of the range is the worksheet.
.LeftMargin = Application.CentimetersToPoints(0.1)
.RightMargin = Application.CentimetersToPoints(0.1)
.FitToPagesWide = 1
End With
.ExportAsFixedFormat _
Type:=xlTypePDF _
, FileName:=FilePath & "Compare " & FileName & ".pdf" _
, Quality:=xlQualityStandard _
, IncludeDocProperties:=True _
, IgnorePrintAreas:=False _
, OpenAfterPublish:=True
End With
End Sub

Related

VBA Excel hide sheets with some name when printing PDF

I have a problem with sheet hiding. I want to print the document, which includes the sheets with a similar name.
I did something like this:
Sub DPPtoPDF()
Dim ws As Worksheet
Sheets("Readme").Visible = False
Sheets("Asbuilt Photos 1").Visible = False
Sheets("Asbuilt Photos 2").Visible = False
Sheets("Splicing Photos").Visible = False
Sheets("Sign Off Sheet").Visible = False
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "OTDR*" Then
ws.Visible = False
End If
Next was
ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & "\" & ThisWorkbook.Name, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
Sheets("Readme").Visible = True
Sheets("Asbuilt Photos 1").Visible = True
Sheets("Asbuilt Photos 2").Visible = True
Sheets("Splicing Photos").Visible = True
Sheets("Sign Off Sheet").Visible = True
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "OTDR*" Then
ws.Visible = True
End If
Next was
Sheets("Frontsheet").Select
End Sub
following the solutions:
https://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.visible
Unhide sheets names using VBA whose name contain specific word
https://excelchamps.com/vba/hide-sheet/
it returns over 2000 pages in my PDF document
What have I done wrong in the code?
I have about 30 sheets at most. How can I exclude (hide) the following sheets from printing it as the PDF?
I would suggest to do it with the print function. Here is my code:
Sub DPPtoPDF()
Dim ws As Worksheet
Sheets("Readme").Visible = False
Sheets("Asbuilt Photos 1").Visible = False
Sheets("Asbuilt Photos 2").Visible = False
Sheets("Splicing Photos").Visible = False
Sheets("Sign Off Sheet").Visible = False
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "OTDR*" Then
ws.Visible = False
End If
Next ws
Dim arr As Variant
Dim i As Integer
Dim counter As Integer
ReDim arr(counter)
'Add all visible sheets to an array (arr)
For i = 1 To Worksheets.Count
If Worksheets(i).Visible = True Then
ReDim Preserve arr(counter)
arr(counter) = Worksheets(i).Name
counter = counter + 1
End If
Next
'select all sheets the array contains
Worksheets(arr).Select
'set the path
printpath = ThisWorkbook.Path & "\" & ThisWorkbook.Name
'print the selection
ThisWorkbook.Windows(1).SelectedSheets.PrintOut PrintToFile:=True, PrToFileName:=printpath, ActivePrinter:="Microsoft Print to PDF", IgnorePrintAreas:=True
Sheets("Readme").Visible = True
Sheets("Asbuilt Photos 1").Visible = True
Sheets("Asbuilt Photos 2").Visible = True
Sheets("Splicing Photos").Visible = True
Sheets("Sign Off Sheet").Visible = True
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "OTDR*" Then
ws.Visible = True
End If
Next was
Sheets("Frontsheet").Select
End Sub
You just need to select multiple sheets and make only the selected sheets into a pdf file.
Sub DPPtoPDF()
Dim ws As Worksheet
Dim vName() As Variant
Dim n As Integer
ReDim vName(1 To 1000)
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "OTDR*" Or ws.Name = "Readme" Or ws.Name = "Asbuilt Photos 1" _
Or ws.Name = "Asbuilt Photos 2" Or ws.Name = "Splicing Photos" _
Or ws.Name = "Sign Off Sheet" Then
Else
n = n + 1
vName(n) = ws.Name
End If
Next ws
ReDim Preserve vName(1 To n)
Sheets(vName).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & "\" & "test.pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
Print Specified Worksheets
Option Explicit
Sub DPPtoPDF()
Const SheetNamesList As String = "Readme,Asbuilt Photos 1," _
& "Asbuilt Photos 2,Splicing Photos,Sign Off Sheet"
Const crit As String = "OTDR*"
Dim wb As Workbook: Set wb = ThisWorkbook
Dim SheetNames() As String: SheetNames = Split(SheetNamesList, ",")
Dim sh As Object
Dim snms() As String
Dim shName As String
Dim n As Long
For Each sh In wb.Sheets
shName = sh.Name
If Not UCase(shName) Like crit Then
If IsError(Application.Match(shName, SheetNames, 0)) Then
ReDim Preserve snms(n)
snms(n) = shName
n = n + 1
End If
End If
Next sh
' Copy to new workbook
wb.Worksheets(snms).Copy
With ActiveWorkbook
.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=wb.Path & "\" & wb.Name, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
.Close False
End With
wb.Sheets("Frontsheet").Select
End Sub

Looping a recorded macro in Excel

I am not familiar with VBA so please forgive the simplicity of this question. I have a recorded macro which selects, opens then saves a file from a hyperlink in one of my columns. I just want to make a loop to repeat this macro down all of the rows in the worksheet which have data in them. Below is the code for the recorded macro, thank you all for your assistance.
Sub Extract()
'
'Extract Macro
'
'
Range("D2").Select
Selection.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
Workbooks.Open Filename:= _
"https://channele.corp.etradegrp.com/communities/teams02/performance-monitoring/TPEF%20Library/A2Consulting_Tech_5650_VSAF.xlsm"
ActiveWindow.Visible = False
Windows("A2Consulting_Tech_5650_VSAF.xlsm").Visible = True
ChDir "O:\Procurement Planning\QA"
ActiveWorkbook.SaveAs Filename:= _
"O:\Procurement Planning\QA\Copy of A2Consulting_Tech_5650_VSAF.xlsm", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
ActiveWindow.Close
End Sub
Something like this might work already:
Sub Extract()
Dim RngTarget As Range
Dim StrFileName As String
Set RngTarget = Range("D2")
Do Until RngTarget.Value = ""
RngTarget.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
Workbooks.Open Filename:=RngTarget.Value
StrFileName = Split(RngTarget.Value, "/")(UBound(Split(RngTarget.Value, "/")))
Windows(StrFileName).Visible = True
Workbooks(StrFileName).SaveAs Filename:="O:\Procurement Planning\QA\Copy of " & Split(StrFileName, ".")(0) & ".xlsm", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
CreateBackup:=False
Workbooks(StrFileName).Close
Set RngTarget = RngTarget.Offset(1, 0)
Loop
End Sub

Print Selected Sheets only... but Active Sheet keeps printing instead

I'm trying to loop through all active sheets and save them as separate PDFs.
dim ws as worksheet
dim path as string
...
For Each ws In ActiveWindow.SelectedSheets
ws.ExportAsFixedFormat _
xlTypePDF, _
Filename:=path & ws.Name, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, _
OpenafterPublish:=False
Next
It kind of works:
A PDF file is created for each selected sheet in the correct folder... but...
The contents of those PDF files are all the same. It is the Active Sheet being printed each time but with a different filename.
How to fix this? Keep in mind, I only want selected sheets to print.
EDIT: I'm too new to upvote. Thanks for your answers!
You need to Select the sheet before printing out.
Just add the command ws.Select right before ws.ExportAsFixedFormat and it will work:
For Each ws In ActiveWindow.SelectedSheets
ws.Select '<-- the only thing you have to add.
ws.ExportAsFixedFormat _
xlTypePDF, _
Filename:=path & ws.Name, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, _
OpenafterPublish:=False
Next
Apart for this:
Tip 1: to avoid seeing the sheets jumping over and over, you can add Application.ScreenUpdating = False before the loop starts and then setting it back to Application.ScreenUpdating = True at the end of the loop.
Tip 2: for user friendliness, you can get the currently active sheet at the beginning of the loop with Dim currentlySelectedSheet As Worksheet: Set currentlySelectedSheet = ActiveSheet and when the loop ends, you just select it back with currentlySelectedSheet.Select so that the user won't see anything change in their screen when running your macro.
Option Explicit
Sub Save_SelectedSheets_AsPdf()
Dim ws As Worksheet
Dim path As String
Dim actSheet As Worksheet
'...
Set actSheet = ActiveSheet
For Each ws In ActiveWindow.SelectedSheets
ws.Select
ws.ExportAsFixedFormat _
xlTypePDF, _
Filename:=path & ws.Name, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, _
OpenafterPublish:=False
Next
actSheet.Select
End Sub
Sub Create_5_Sheets_and_name_them()
Dim iCt As Integer
For iCt = 2 To 5
Sheets.Add after:=Sheets(Sheets.Count)
ActiveSheet.Name = "Sh" & iCt
Range("A1").Value = ActiveSheet.Name
Next iCt
End Sub
you can specify it like this before you export it to pdf

Avoiding 'Save As' dialog box in Excel VBA script

I have cobbled together a VBA script that loops through a list of data, changing the value of a single cell on a summary page. That cell drives a number of formulas. After each iteration, the cell range of interest is saved off as a PDF.
I am looking to avoid having to manually hit enter every time the 'save as' dialog box is generated on each loop. Once I deploy this script, I could be looking at 1k+ iterations.
Sub AlterID()
Dim ws As Worksheet
Dim strPath As String
Dim myFile As Variant
Dim strFile As String
Set ws = Worksheets("Summary Data")
For Each c In Worksheets("Data").Range("A2:A11").Cells
Worksheets("Summary Data").Range("B1").Value = c.Value
strFile = ws.Range("D3").Value
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.Range("D3:H9").Select
Selection.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End If
Next
End Sub
Sub AlterID()
Dim ws As Worksheet, c As Range
Dim strFile As String
Set ws = Worksheets("Summary Data")
For Each c In Worksheets("Data").Range("A2:A11").Cells
ws.Range("B1").Value = c.Value
strFile = ThisWorkbook.Path & "\" & ws.Range("D3").Value
ws.Range("D3:H9").ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next
End Sub
Have you tried turning off application alerts?
Application.DisplayAlerts = False 'before your code
Application.DisplayAlerts = True 'after your code
Edit 1
Here is a sub I use to save a file to a PDF
Sub SaveAsPDF()
Dim myValue As Variant
Dim mySheets As Variant
mySheets = Array("Report")
For Each sh In mySheets
Sheets(sh).PageSetup.Orientation = xlLandscape
Next
uid = InputBox("Enter your UID")
uid = StrConv(uid, vbProperCase)
Application.PrintCommunication = False
With Sheets("Report").PageSetup
.FitToPagesWide = 1
.FitToPagesTall = False
End With
Application.PrintCommunication = True
Dim fName As String
fName = "HMB SOX report for week ending " & ActiveSheet.Range("H4").Text
Call selectPage("Report")
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, fileName:= _
"C:\Users\" & uid & "\Desktop\" & fName, :=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, Publish:=False
End With
End Sub

Excel VBA to Save Selected Sheets in Combination as PDFs

I have a workbook with many worksheets. I would like to save as two-page PDFs, where the first page is Worksheet 1, and the second page is Worksheets 2-x. My code currently only allows me to save individual PDFs for each worksheet in the workbook. I am wondering what to add to it to make it do this. Can anyone share some advice?
Thanks!
Option Explicit
Sub createPDFfiles()
Dim ws As Worksheet
Dim Fname As String
For Each ws In ActiveWorkbook.Worksheets
On Error Resume Next
Fname = "C:\Folder\" & ws.Name & "Report" & Format(Date, "yyyy-mm-dd") & ".pdf"
ws.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=Fname, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False
Next ws
End Sub
You are enumerating through the worksheets and doing your save inside that loop. That is why you are getting one PDF per worksheet. Try using just workbook instead of ActiveWorkbook.Worksheets.
Gah. It was staring me in the face the whole time. I amended the code to include a selection, and named the second worksheet ws.Name. Final script looks like this:
Option Explicit
Sub createPDFfiles()
Dim ws As Worksheet
Dim Fname As String
For Each ws In ActiveWorkbook.Worksheets
On Error Resume Next
Fname = "C:\Folder\" & ws.Name & "Report" & Format(Date, "yyyy-mm-dd") & ".pdf"
Sheets(Array("Sheet1", ws.Name)).Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=Fname, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False
Next ws
End Sub
Thanks for your help everyone!

Resources