VBA Excel hide sheets with some name when printing PDF - excel

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

Related

Pastespecial of range class fails on only one computer

I have a macro that prints a chart to pdf by copying the chart to a new sheet (wstemp) and printing the new sheet. The macro works fine on my computer and my wife's, but not on the client's. He continues to get the '1004' error "paste method of range class failed". Code below, the error is on the paste line. Any thoughts would be greatly appreciated.
Sub PrintPDFLDRBD_Chart1()
'
' prints my ldr bd
'
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim ch1 As Shape
Dim pth, nme, fn, lft, chd As String
Dim wsref, wstemp As Worksheet
Set wsref = ThisWorkbook.Sheets("SheetA")
Set ch1 = wsref.Shapes("SheetAChart1")
pth = ThisWorkbook.path
fn = pth & "\" & "SheetA_ch1"
Set wstemp = Sheets.Add
ch1.Copy
wstemp.Range("A1").PasteSpecial
With wstemp.PageSetup
.RightHeader = Format(Now, "MMMM DD, YYYY HH:MM:SS")
.Zoom = False
.FitToPagesTall = 1
.FitToPagesWide = 1
End With
wstemp.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
fn, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=True, OpenAfterPublish:=True
wstemp.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

Print to PDF (A3 landscape) export size ends up at 160cm x 110cm

I have large spreadsheet that I'm looping through and printing each page to a pdf report.
I'm trying to print them A3 Landscape, however the actual export size is far larger than an A3 page.
Any suggestions I what I'm doing wrong?
Here is my current code:
Sub printChartsA3()
Application.ScreenUpdating = False
Dim sPrintArea As String
Dim wks As Worksheet
Const path As String = "E:\A3 Charts\"
sPrintArea = "A1:BM69"
For Each wks In Worksheets
Application.PrintCommunication = False
wks.PageSetup.PaperSize = xlPaperA3
wks.PageSetup.Orientation = xlLandscape
wks.PageSetup.LeftMargin = Application.InchesToPoints(0.25)
wks.PageSetup.RightMargin = Application.InchesToPoints(0.25)
wks.PageSetup.PrintArea = sPrintArea
wks.PageSetup.Zoom = False
wks.PageSetup.FitToPagesWide = 1
'wks.PageSetup.FitToPagesTall = 1 'not sure if this one is needed?
Application.PrintCommunication = True
wks.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=path & wks.Name & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next
Set wks = Nothing
Application.ScreenUpdating = True
End Sub

VBA - Change Cell based on a list and then save a new workbook based on that cell / list

I have a workbook already with a macro that does several things based on a cell value:
When i change a cell value (its a store name) the code will filter several sheets with, just to show the store of that specific cell, then hides several sheets.
Just showing 2 specific sheets.
And in the end of the code i save a new workbook with the name of that store.
My question is:
Is it possible to change my code (shown below), so i dont have to write manually the name of the store, ie, i want that the macro sees a list of stores, then change the cell with each store, do all the tasks i want, and then writes a new workbook with that store name, and so on, until the end of the list store?
Thank you so much
(PS: im new in vba, so my code probably is a little rough around the edges)
Sub Nova_loja()
Dim sht As Worksheet
Dim Fname As String
Dim Cell As Range, cRange As Range
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
'copy past in values
With Range("K44:L66")
.Cells.Copy
.Cells.PasteSpecial xlPasteValues
End With
Application.CutCopyMode = False
'filter and delete
Sheets("BD Geral").Select
ActiveSheet.ListObjects("Table2").Range.AutoFilter Field:=52, Criteria1:="<>" & Worksheets("Tabela - Média Mensal").Range("B2").value, Operator:=xlFilterValues
Application.DisplayAlerts = False
ActiveSheet.ListObjects("Table2").DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ActiveSheet.ListObjects("Table2").AutoFilter.ShowAllData
'filter and delete
Sheets("BD BONUS_MALUS").Select
ActiveSheet.ListObjects("Table35").Range.AutoFilter Field:=3, Criteria1:="<>" & Worksheets("Tabela - Média Mensal").Range("B1").value, Operator:=xlFilterValues
Application.DisplayAlerts = False
ActiveSheet.ListObjects("Table35").DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ActiveSheet.ListObjects("Table35").AutoFilter.ShowAllData
'filter and delete
Sheets("BD NPS").Select
ActiveSheet.ListObjects("Table3").Range.AutoFilter Field:=2, Criteria1:="<>" & Worksheets("Tabela - Média Mensal").Range("B1").value, Operator:=xlFilterValues
Application.DisplayAlerts = False
ActiveSheet.ListObjects("Table3").DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ActiveSheet.ListObjects("Table3").AutoFilter.ShowAllData
Sheets("BD Dept").Select
ActiveSheet.ListObjects("Table4").Range.AutoFilter Field:=8, Criteria1:="<>" & Worksheets("Tabela - Média Mensal").Range("B1").value, Operator:=xlFilterValues
Application.DisplayAlerts = False
ActiveSheet.ListObjects("Table4").DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ActiveSheet.ListObjects("Table4").AutoFilter.ShowAllData
'refresh pivots
ThisWorkbook.RefreshAll
'hide sheets
For Each sht In ThisWorkbook.Worksheets
If sht.Name <> "Dashboard" And sht.Name <> "Tabela - Média Mensal" Then
sht.Visible = xlSheetVeryHidden
End If
Next sht
'protect sheets
For Each sht In ActiveWorkbook.Sheets
sht.Protect Password:="fnacrh", AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True
Next
'leave active main worksheet
Sheets("Dashboard").Select
'save as with new name
Application.DisplayAlerts = False
Fname = ThisWorkbook.Path & "\" & "02.VIM_REPORT MENSAL - " & Worksheets("aux").Range("V2") & " - " & Worksheets("aux").Range("V3") & ".xlsx"
ActiveWorkbook.SaveAs Filename:=Fname, FileFormat:=xlWorkbookDefault
Application.DisplayAlerts = True
Application.DisplayStatusBar = True
Application.ScreenUpdating = True
End Sub
Thank you so much
The next code would do what I understood you need.
Copy the next code in a module of another workbook, different from the one to be processed, and run AutomaticallySelectStore procedure. An InputBox will appear asking to select the number from the right side of the workbook name to be processed.
Sub AutomaticallySelectStore()
Dim w As Workbook, Wb As Workbook, sh As Worksheet, store As Variant, Arr As Variant, Ans As String
Dim i As Long, strWorkb As String, strWbName As String, strWbPath As String, nrStores As Long
strWorkb = "Please write the number of the workbook needed to be processed:" & vbCrLf & vbCrLf
For Each Wb In Workbooks
i = i + 1
strWorkb = strWorkb & Wb.name & " - " & i & vbCrLf
Next
strWorkb = left(strWorkb, Len(strWorkb) - 1)
Ans = InputBox(strWorkb, "Necessary workbook selection", 1)
If Ans = "" Then MsgBox "You did not select anything...", vbInformation, "No workbook selected": Exit Sub
If Not IsNumeric(Ans) Then
MsgBox "You must write the number from the right side of the needed workbook name!", vbInformation, _
"Wrong choice...": Exit Sub
ElseIf Ans > Workbooks.Count Then
MsgBox "You must write a number less or equal with " & Workbooks.Count, vbInformation, _
"Wrong chosen number": Exit Sub
End If
Set w = Workbooks(CLng(Ans))
On Error Resume Next
Set sh = w.Worksheets("aux")
If Err.Number <> 0 Then
Err.Clear: On Error GoTo 0
MsgBox "The chosen workbook looks to be wrong..." & vbCrLf & _
" Worksheet ""Tabela - Média Mensal"" is missing.", vbInformation, _
"Wrong workbook or necessary worksheet missing": Exit Sub
End If
On Error GoTo 0
strWbName = w.FullName
nrStores = sh.Range("AF2").End(xlDown).Row
Arr = sh.Range("AF2:AF" & nrStores)
w.Activate
i = 0
Application.Calculation = xlCalculationManual
For Each store In Arr
i = i + 1
Nova_loja strWbName, store, i, nrStores - 1
Next
Application.Calculation = xlCalculationAutomatic
Application.StatusBar = "Ready..."
End Sub
Sub Nova_loja(strWbName As String, store As Variant, No As Long, NrPag As Long)
Dim sht As Worksheet, fName As String, Cell As Range, cRange As Range
Dim w As Workbook, Wb As Workbook, boolFound As Boolean, shortName As String
Dim Arr As Variant, shAr As Worksheet, shortWbName As String
shortWbName = Right(strWbName, Len(strWbName) - InStrRev(strWbName, "\"))
For Each Wb In Workbooks
If Wb.FullName = strWbName Then
Set w = Wb: boolFound = True: Exit For
End If
Next
If Not boolFound Then
Set w = Workbooks.Open(strWbName)
End If
Application.ScreenUpdating = False
Application.StatusBar = "Working on " & store & " store (" & No & " of " & NrPag & ")..."
Application.CalculateBeforeSave = True
Set shAr = Workbooks(shortWbName).Worksheets("aux")
Arr = shAr.Range("K44:L66")
shAr.Range("K44:L66") = Arr
Sheets("Tabela - Média Mensal").Range("B2").Value = store
Sheets("BD Geral").ListObjects("Table2").Range.AutoFilter field:=52, Criteria1:="<>" & store, _
Operator:=xlFilterValues
Application.DisplayAlerts = False
Sheets("BD Geral").ListObjects("Table2").DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Sheets("BD Geral").ListObjects("Table2").AutoFilter.ShowAllData 'it returns an error if no filter is applied
Application.DisplayAlerts = True
'filter and delete
Sheets("BD BONUS_MALUS").ListObjects("Table35").Range.AutoFilter field:=3, Criteria1:="<>" & Worksheets("Tabela - Média Mensal").Range("B1").Value, Operator:=xlFilterValues
Application.DisplayAlerts = False
Sheets("BD BONUS_MALUS").ListObjects("Table35").DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
Sheets("BD BONUS_MALUS").ListObjects("Table35").AutoFilter.ShowAllData
'filter and delete
Sheets("BD NPS").ListObjects("Table3").Range.AutoFilter field:=2, Criteria1:="<>" & Worksheets("Tabela - Média Mensal").Range("B1").Value, Operator:=xlFilterValues
Application.DisplayAlerts = False
Sheets("BD NPS").ListObjects("Table3").DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
Sheets("BD NPS").ListObjects("Table3").AutoFilter.ShowAllData
'This sheet does not contain any "Table"...
Sheets("BD Dept").ListObjects("Table4").Range.AutoFilter field:=8, Criteria1:="<>" & Worksheets("Tabela - Média Mensal").Range("B1").Value, Operator:=xlFilterValues
Application.DisplayAlerts = False
Sheets("BD Dept").ListObjects("Table4").DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
Sheets("BD Dept").ListObjects("Table4").AutoFilter.ShowAllData
'hide sheets
For Each sht In w.Worksheets
If sht.name <> "Dashboard" And sht.name <> "Tabela - Média Mensal" Then
sht.Visible = xlSheetVeryHidden
End If
Next sht
'protect sheets
For Each sht In ActiveWorkbook.Sheets
sht.Protect Password:="fnacrh", AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True
Next
'leave active main worksheet
Sheets("Dashboard").Select
w.RefreshAll
shortName = "02.VIM_REPORT MENSAL - " & store & " - " & Worksheets("aux").Range("V3") & ".xlsx"
fName = w.Path & "\" & shortName
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=fName, FileFormat:=xlWorkbookDefault
Workbooks(shortName).Close , False
Application.DisplayAlerts = True
Application.DisplayStatusBar = True
Application.ScreenUpdating = True
End Sub
Please, test it and confirm if it works as expected.
If not, mention what wrong happens.
Would that 'list of stores' be another excel workbook/sheet?
Do we have to deduce where the 'store' in discussion exists in your workbook?
Isn't it better you to describe where the change must be done?
Of course, this is not an answer but I do not know how else I can clarify the issue...
Sub AutomaticallySelectStore()
Dim W As Workbook, Sh As Worksheet, store As Variant, Arr As Variant
Set W = ActiveWorkbook
Set Sh = W.Worksheets("Tabela - Média Mensal")
Arr = Sh.Range("AF2:AF" & Sh.Range("AF2").SpecialCells(xlCellTypeLastCell).Row)
For Each store In Arr
Nova_loja store
Next
End Sub
Sub Nova_loja(store As Variant)
Dim sht As Worksheet, Fname As String, Cell As Range, cRange As Range
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
With Range("K44:L66")
.Cells.Copy
.Cells.PasteSpecial xlPasteValues
End With
Application.CutCopyMode = False
'filter and delete
Sheets("BD Geral").Select
ActiveSheet.ListObjects("Table2").Range.AutoFilter Field:=52, Criteria1:="<>" & store, Operator:=xlFilterValues
Application.DisplayAlerts = False
ActiveSheet.ListObjects("Table2").DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ActiveSheet.ListObjects("Table2").AutoFilter.ShowAllData
'filter and delete
Sheets("BD BONUS_MALUS").Select
ActiveSheet.ListObjects("Table35").Range.AutoFilter Field:=3, Criteria1:="<>" & Worksheets("Tabela - Média Mensal").Range("B1").Value, Operator:=xlFilterValues
Application.DisplayAlerts = False
ActiveSheet.ListObjects("Table35").DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ActiveSheet.ListObjects("Table35").AutoFilter.ShowAllData
'filter and delete
Sheets("BD NPS").Select
ActiveSheet.ListObjects("Table3").Range.AutoFilter Field:=2, Criteria1:="<>" & Worksheets("Tabela - Média Mensal").Range("B1").Value, Operator:=xlFilterValues
Application.DisplayAlerts = False
ActiveSheet.ListObjects("Table3").DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ActiveSheet.ListObjects("Table3").AutoFilter.ShowAllData
Sheets("BD Dept").Select
ActiveSheet.ListObjects("Table4").Range.AutoFilter Field:=8, Criteria1:="<>" & Worksheets("Tabela - Média Mensal").Range("B1").Value, Operator:=xlFilterValues
Application.DisplayAlerts = False
ActiveSheet.ListObjects("Table4").DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ActiveSheet.ListObjects("Table4").AutoFilter.ShowAllData
'refresh pivots
ThisWorkbook.RefreshAll
'hide sheets
For Each sht In ThisWorkbook.Worksheets
If sht.Name <> "Dashboard" And sht.Name <> "Tabela - Média Mensal" Then
sht.Visible = xlSheetVeryHidden
End If
Next sht
'protect sheets
For Each sht In ActiveWorkbook.Sheets
sht.Protect Password:="fnacrh", AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True
Next
'leave active main worksheet
Sheets("Dashboard").Select
'save as with new name
Application.DisplayAlerts = False
Fname = ThisWorkbook.Path & "\" & "02.VIM_REPORT MENSAL - " & Worksheets("aux").Range("V2") & " - " & Worksheets("aux").Range("V3") & ".xlsx"
ActiveWorkbook.SaveAs Filename:=Fname, FileFormat:=xlWorkbookDefault
Application.DisplayAlerts = True
Application.DisplayStatusBar = True
Application.ScreenUpdating = True
End Sub
So, you must run 'AutomaticallySelectStore' procedure and wait...
I do not have such a file in order to test it, so, it is a code based only on VBA logic and my understanding about your situation.
Depending on how big are your workbooks it may load your system RAM and CPU, working continuously. I am waiting for some feedback.
The initial code can also be optimized a little, but let us see how it works now.

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

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

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

Resources