Copying Multiple Versions of the same Excel Page into one PDF - vba

I have a one page excel file that changes based on a drop down selection. I need to be able to export each data set into one PDF. So, I am looking for a macro that would loop through each selection in the drop down menu and have each of those data sets save into a multi page PDF file.
My thought would be to create the loop and have each version saved as a temporary worksheet. Then I could use
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\tempo.pdf", Quality:= xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
to save all the sheets as one PDF but then I would need to delete all the temp files.
Thanks,
Chris

I suggest exporting them all individually to PDF into a temp directory, stitching them together using Adobe's COM automation library (assuming you have Pro), then deleting the temp folder.
Public Sub JoinPDF_Folder(ByVal strFolderPath As String, ByVal strOutputFileName As String)
On Error GoTo ErrHandler:
Dim AcroExchPDDoc As Object, _
AcroExchInsertPDDoc As Object
Dim strFileName As String
Dim iNumberOfPagesToInsert As Integer, _
iLastPage As Integer
Set AcroExchPDDoc = CreateObject("AcroExch.PDDoc")
Dim strFirstPDF As String
' Get the first pdf file in the directory
strFileName = Dir(strFolderPath + "*.pdf", vbNormal)
strFirstPDF = strFileName
' Open the first file in the directory
If Not (AcroExchPDDoc.Open(strFolderPath & strFileName)) Then
Err.Raise 55555, "JoinPDF_Folder", "Could not open PDF for joining"
End If
' Get the name of the next file in the directory [if any]
If strFileName <> "" Then
strFileName = Dir
' Start the loop.
Do While strFileName <> ""
' Get the total pages less one for the last page num [zero based]
iLastPage = AcroExchPDDoc.GetNumPages - 1
Set AcroExchInsertPDDoc = CreateObject("AcroExch.PDDoc")
' Open the file to insert
If Not (AcroExchInsertPDDoc.Open(strFolderPath & strFileName)) Then
Err.Raise 55555, "JoinPDF_Folder", "Could not open PDF for joining"
End If
' Get the number of pages to insert
iNumberOfPagesToInsert = AcroExchInsertPDDoc.GetNumPages
' Insert the pages
AcroExchPDDoc.InsertPages iLastPage, AcroExchInsertPDDoc, 0, iNumberOfPagesToInsert, True
' Close the document
AcroExchInsertPDDoc.Close
' Delete the document
Kill strFolderPath & strFileName
' Get the name of the next file in the directory
strFileName = Dir
Loop
' Save the entire document as the strOutputFileName using SaveFull [0x0001 = &H1]
If Not (AcroExchPDDoc.Save(PDSaveFull, strOutputFileName)) Then
Err.Raise 55556, "JoinPDF_Folder", "Could not save joined PDF"
End If
End If
' Close the PDDoc
AcroExchPDDoc.Close
Kill strFolderPath & strFirstPDF
CallStack.Pop
Exit Sub
ErrHandler:
GlobalErrHandler
End Sub

Here was my solution:
Sub LoopThroughDD()
'Created by Chrismas007
Dim DDLCount As Long
Dim TotalDDL As Long
Dim CurrentStr As String
TotalDDL = Sheets("Report").DropDowns("Drop Down 10").ListCount
'Loops through DropDown stores
For DDLCount = 1 To TotalDDL
Sheets("Report").DropDowns("Drop Down 10").Value = DDLCount
CurrentStr = "Report" & DDLCount
'Creates a copy of each store and pastes them in a new worksheet
Sheets.Add(After:=Sheets(Worksheets.Count)).Name = "Report" & DDLCount
Sheets("Report").Columns("D:V").Copy
Sheets(CurrentStr).Columns("A:S").Insert Shift:=xlToRight
Sheets(CurrentStr).Range("A1:S98").Select
Selection.Copy
Sheets(CurrentStr).Range("A1:S98").Select
Selection.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Sheets(CurrentStr).PageSetup.PrintArea = "$A$1:$S$98"
'Sets worksheet to one page
With Sheets(CurrentStr).PageSetup
.LeftMargin = Application.InchesToPoints(0.5)
.RightMargin = Application.InchesToPoints(0.5)
.TopMargin = Application.InchesToPoints(0.5)
.BottomMargin = Application.InchesToPoints(0.5)
.HeaderMargin = Application.InchesToPoints(0)
.FooterMargin = Application.InchesToPoints(0)
.FitToPagesWide = 1
.FitToPagesTall = 1
.Zoom = False
.CenterHorizontally = True
.CenterVertically = True
End With
Next DDLCount
'Because only visable worksheets will be captured on PDF dump, need to hide temporarily
Sheets("Report").Visible = False
Dim TheOS As String
Dim dd As DropDown
'Going to name the file as the rep name so grabbing that info here
Set dd = Sheets("Report").DropDowns("Drop Down 2")
TheOS = Application.OperatingSystem
'Select all visible worksheets and export to PDF
Dim ws As Worksheet
For Each ws In Sheets
If ws.Visible Then ws.Select (False)
Next
If InStr(1, TheOS, "Windows") > 0 Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & "\" & dd.List(dd.ListIndex), Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
Else
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & ":" & dd.List(dd.ListIndex), Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
End If
'Unhide our original worksheet
Sheets("Report").Visible = True
TotalDDL = Sheets("Report").DropDowns("Drop Down 10").ListCount
'Delete all temp worksheets
For DDLCount = 1 To TotalDDL
CurrentStr = "Report" & DDLCount
Application.DisplayAlerts = False
Sheets(CurrentStr).Delete
Application.DisplayAlerts = True
Next DDLCount
DDLCount = Empty
End Sub

Related

How to set fixed margins on Excel VBA code (PDF is printing in 2 pages instead of 1)

I have an Excel file which has a button "Generate PDF" that runs a macro to print a certain sheet (lets call it "QUOTE") into a PDF. This sheet is shown to be well limited in margins and in my computer the created PDF has the perfect structure: everything is well included in 1 page. However, in some other computers, when the PDF is created, everything does not fit into 1 page and a 2nd page is created with a bit of content. Here is the code (including the attempts to fix this problem by limiting the margins):
Sub Excel_Export_Proposal()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim wsCOTIZACION As Worksheet
Dim Proposalname As String
Dim iVis As XlSheetVisibility
Dim xlName As Excel.Name
Dim FolderPath As String
Dim myRange As String
Set wsQUOTE = ThisWorkbook.Sheets("QUOTE")
FolderPath = ActiveWorkbook.Path & "\"
Proposalname = "Quote for " & CStr(Range("B2").Value)
wsQUOTE.PageSetup.PrintArea = myRange
With wsQUOTE.PageSetup
.FitToPagesTall = 1
.FitToPagesWide = False
.Zoom = False
.LeftMargin = Application.InchesToPoints(0.7)
.RightMargin = Application.InchesToPoints(0.4)
.BottomMargin = Application.InchesToPoints(0.75)
.TopMargin = Application.InchesToPoints(0.75)
End With
'Proposal
Application.ScreenUpdating = False
wb.Unprotect
With wsQUOTE
iVis = .Visible
.Visible = xlSheetVisible
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ActiveWorkbook.Path & "\" & Proposalname & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=True, _
OpenAfterPublish:=True
.Visible = iVis
wsQUOTE.Activate
End With
wb.Protect
Application.ScreenUpdating = True
End Sub
Can somebody help me fixing this problem? I would like that the sheet would we printed perfectly regardless of the computer or software in which is generated...
In order to have the procedure Excel_Export_Proposal including the PrintingArea in one page always the following adjustments should be applied:
Set the printing area correctly:
This line sets the printing area: wsQUOTE.PageSetup.PrintArea = myRange
However no value is assigned to the variable myRange before this line, therefore the PrintArea is set to "" which is equivalent to setting it to the entire UsedRange of the wsQUOTE sheet.
To ensure that the entire PrintArea is printed in one page the FitToPagesTall and FitToPagesWide must be set to 1
Replace .FitToPagesWide = False with .FitToPagesWide = 1
And remove .Zoom = False as it has not effect after setting FitToPagesTall and FitToPagesWide to 1
To ensure that the ExportAsFixedFormat method uses the print areas as defined in the target excel file set the IgnorePrintAreas parameter to False.
Replace this line IgnorePrintAreas:=True, _ with this line IgnorePrintAreas:=False, _
Below is the revised procedure:
Sub Excel_Export_Proposal_Revised()
Dim wb As Workbook, wsQuote As Worksheet
Dim myRange As String, Proposalname As String, FolderPath As String
Dim iVis As XlSheetVisibility
Set wb = ThisWorkbook
Set wsQuote = wb.Sheets("QUOTE")
FolderPath = wb.Path & "\"
Proposalname = "Quote for " & wsQuote.Range("B2").Value2
'Update myRange with the address of the range to be printed
myRange = "$B$2:$O$58" 'Change as required
Application.ScreenUpdating = False
With wsQuote.PageSetup
.PrintArea = myRange
.FitToPagesTall = 1
.FitToPagesWide = 1 'Set FitToPagesWide to 1
.LeftMargin = Application.InchesToPoints(0.7)
.RightMargin = Application.InchesToPoints(0.4)
.TopMargin = Application.InchesToPoints(0.75)
.BottomMargin = Application.InchesToPoints(0.75)
End With
'Proposal
wb.Unprotect
With wsQuote
iVis = .Visible
.Visible = xlSheetVisible
.Activate
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=FolderPath & Proposalname & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
.Visible = iVis
End With
wb.Protect
Application.ScreenUpdating = True
End Sub
See following pages for additional information on the resources used:
Worksheet.ExportAsFixedFormat Method (Excel)
PageSetup Object (Excel)

Method 'ExportAsFixedFormat' of object '_worksheet' failed

Here are my code to export all sheets of excel to PDF:
Sub printing()
Dim i As Integer, wkb As String, head As String, nm As String
Dim ws As Worksheet
Application.ScreenUpdating = False
'get folder path
wkb = InputBox("Enter folder path:", , ActiveWorkbook.Path)
If Right(wkb, 1) <> Application.PathSeparator Then wkb = wkb & Application.PathSeparator
'head of file name
head = InputBox("Enter head of file name", , "Test")
Application.DisplayAlerts = False
For Each ws In ActiveWorkbook.Worksheets
'ActiveWorkbook.Sheets.Count
If ws.Visible = True Then
ws.Select
nm = ws.Range("A1")
If nm <> "" Then
'save
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
FileName:=wkb & head & nm & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End If
Application.DisplayAlerts = False
End If
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Done"
End Sub
I run this macro on my Mac and my friend's Mac, But my Mac is pass,and my friend's mac not pass and occured an errors:
Run time error '1004':
Method 'ExportAsFixedFormat' of object '_worksheet' failed
Can you tell me a solution to fix it?
Thanks.

Macro to copy data from a different workbook

I have a workbook (in Excel 2003 format) with data flowing continuously in three sheets. I want to create a macro in a new workbook (Excel 2010) in which all those data in all the three sheets in the previous workbook to get pasted in a single sheet of my new workbook, one after another. I would prefer the macro to open a dialog box to browse the file where the data is actually present. Can anyone help me please?
While searching I found something like given below. But that is not the one I want exactly.
Sub Open_Workbook()
Dim myFile As String
myFile = Application.GetOpenFilename _
(Title:="Please choose a file to open", _
FileFilter:="Excel Files .xls (.xls),")
If myFile = False Then
MsgBox "No file selected.", vbExclamation, "Sorry!"
Exit Sub
Else
Workbooks.Open Filename:=myFile
End If
End Sub
I suppose this code will help you
Sub wb_sheets_combine_into_one()
Dim sFileName$, UserName$, oWbname$, oWbname2$, sDSheet$ 'String type
Dim nCountDestination&, nCount&, nCountCol& 'Long type
Dim oSheet As Excel.Worksheet
Dim oRange As Range
Dim oFldialog As FileDialog
Set oFldialog = Application.FileDialog(msoFileDialogFilePicker)
With oFldialog
If .Show = -1 Then
.Title = "Select File"
.AllowMultiSelect = False
sFileName = .SelectedItems(1)
Else
Exit Sub
End If
End With
'open source workbook
Workbooks.Open sFileName: oWbname = ActiveWorkbook.Name
UserName = Environ("username")
Workbooks.Add: ActiveWorkbook.SaveAs Filename:= _
"C:\Users\" & UserName & _
"\Desktop\Consolidated.xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
oWbname2 = ActiveWorkbook.Name
sDSheet = ActiveSheet.Name
nCountDestination = 1
Workbooks(oWbname).Activate
For Each oSheet In Workbooks(oWbname).Worksheets
oSheet.Activate
sDSheet = ActiveSheet.Name
ActiveSheet.UsedRange.Copy
For Each oRange In ActiveSheet.UsedRange
nCountCol = oRange.Column
Next
Workbooks(oWbname2).Activate
Cells(nCountDestination, 1).PasteSpecial xlPasteAll
nCount = nCountDestination
For Each oRange In ActiveSheet.UsedRange
nCountDestination = oRange.Row + 1
Next
Range(Cells(nCount, nCountCol + 1), _
Cells(nCountDestination - 1, nCountCol + 1)).Value = oSheet.Name
Workbooks(oWbname).Activate
With ActiveWorkbook.Sheets(sDSheet).Tab
.ThemeColor = xlThemeColorAccent1
.TintAndShade = 0
End With
Next
Workbooks(oWbname2).Save: Workbooks(oWbname).Close False
MsgBox "File with consolidated data from workbook " & Chr(10) & _
"[ " & oWbname & " ] saved on your desktop!"
End Sub

VBA Opening multiple workbooks defined by the user with filter restriction

I am new to VBA programming and there are three points i would like to do
1, I would like to restrict file type are ".xls", ".xlsx" or ".csv"
2, I would record the File Name and File path i have selected
3, I have error if MultiSelect:=True instead of False
Here is my code that i have at the moment
Sub Macro1()
Dim FPath As Variant
Dim FName As Variant
FPath = Application.GetOpenFilename( _
FileFilter:="Excel Workbooks, *.xl*", _ #*.xl* | *.csv*
Title:="Choose a Workbook to Open,", _
MultiSelect:=True) #I think we need to set TRUE
FName = Dir(FPath, vbDirectory) # i want to get rid of .csv/ .xls/ .xlsx
Range("A1").Value = FName
If FName <> False Then
Workbooks.Open Filename:=FPath
End If
End Sub
Thanks for your help
Maybe try like this
Sub Macro1()
Dim FName() As Variant
FName = Application.GetOpenFilename( _
FileFilter:="Excel Files (*.xls; *.xlsx; *.csv), *.xls", _
Title:="Choose a Workbook to Open,", _
MultiSelect:=True)
If UBound(FName) > 0 Then
Dim vFile As Variant
For Each vFile In FName
MsgBox getPath(vFile)
MsgBox getFileName(vFile)
Workbooks.Open Filename:=vFile
Next
End If
End Sub
Private Function getPath$(f)
getPath = Left(f, InStrRev(f, "\", -1, 1))
End Function
Private Function getFileName$(f)
Dim wExt$
wExt = Mid(f, Len(getPath(f)) + 1, Len(f) - Len(getPath(f)))
getFileName = Mid(wExt, 1, InStrRev(wExt, ".", -1, 1) - 1)
End Function

How can I export multiple graphs from excel to a single pdf using vba?

I am completely new to VBA and need to export multiple graphs from an excel workbook to a single pdf using vba. I know it's possible to export the graphs as individual pdf's or jpgs but is it possibly to put all graphs from a workbook into one pdf using vba? Any advice would be greatly appreciated as I can't seem to find what I'm looking for elsewhere.
My code so far prints each chart to the pdf, but each chart gets overwritten on the next print. My code is as follows:
Sub exportGraphs()
Dim Ws As Worksheet
Dim Filename As String
Filename = Application.InputBox("Enter the pdf file name", Type:=2)
Sheets("Status and SLA trends").Select
ActiveSheet.ChartObjects("Chart 4").Activate
ActiveChart.ExportAsFixedFormat xlTypePDF, Filename, xlQualityStandard
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.ExportAsFixedFormat xlTypePDF, Filename, xlQualityStandard
Sheets("Current Issue Status").Select
ActiveSheet.ChartObjects("Chart 2").Activate
ActiveChart.ExportAsFixedFormat xlTypePDF, Filename, xlQualityStandard
ActiveSheet.ChartObjects("Chart 5").Activate
ActiveChart.ExportAsFixedFormat xlTypePDF, Filename, xlQualityStandard
ActiveSheet.ChartObjects("Chart 8").Activate
ActiveChart.ExportAsFixedFormat xlTypePDF, Filename, xlQualityStandard
End Sub
In the end I just exported an array of sheets to pdf, as multiple charts were on separate sheets and I didn't need to change how they were formatted. I did it using the following code snippet
Sheets(Array("Current Issue Status", "Status and SLA trends")).Select
Dim saveLocation As String
saveLocation = Application.GetSaveAsFilename( _
fileFilter:="PDF Files (*.pdf), *.pdf")
If saveLocation <> "False" Then
ActiveSheet.ExportAsFixedFormat xlTypePDF, saveLocation, xlQualityStandard
End If
Is this what you are trying?
LOGIC: Copy all charts to a Temp Sheet and then use the Excel's inbuilt tool to create the pdf. Once the pdf is made, delete the temp sheet. This will export multiple graphs from Sheets("Status and SLA trends") to a single pdf using vba.
CODE (TRIED AND TESTED):
Option Explicit
Sub Sample()
Dim ws As Worksheet, wsTemp As Worksheet
Dim chrt As Shape
Dim tp As Long
Dim NewFileName As String
On Error GoTo Whoa
Application.ScreenUpdating = False
NewFileName = "C:\Charts.Pdf"
Set ws = Sheets("Status and SLA trends")
Set wsTemp = Sheets.Add
tp = 10
With wsTemp
For Each chrt In ws.Shapes
chrt.Copy
wsTemp.Range("A1").PasteSpecial
Selection.Top = tp
Selection.Left = 5
tp = tp + Selection.Height + 50
Next
End With
wsTemp.ExportAsFixedFormat Type:=xlTypePDF, Filename:=NewFileName, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
Application.DisplayAlerts = False
wsTemp.Delete
LetsContinue:
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
[Export all charts to one PDF] This worked for me: I extended the sample from here . It copies all charts to a temporary sheet, then changes the page setup (letter /landscape) and resize/re-position each chart to fit separate page borders. Last step is to print this sheet as pdf doc and delete temp sheet.
Sub kartinka()
Dim i As Long, j As Long, k As Long
Dim adH As Long
Dim Rng As Range
Dim FilePath As String: FilePath = ThisWorkbook.Path & "\"
Dim sht As Worksheet, shtSource As Worksheet, wk As Worksheet
'===================================================================
'===================================================================
Sheets.Add After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
ActiveSheet.Name = "ALL"
Set sht = ActiveSheet
'===================================================================
Application.ScreenUpdating = False
'===================================================================
'Excluding ALL tab, copying all charts from all tabs to ALL
For Each wk In Worksheets
If wk.Name <> "ALL" Then
Application.DisplayAlerts = False
j = wk.ChartObjects.Count
For i = 1 To j
wk.ChartObjects(i).Activate
ActiveChart.ChartArea.Copy
sht.Select
ActiveSheet.Paste
sht.Range("A" & 1 + i & "").Select
Next i
Application.DisplayAlerts = True
End If
Next
'===================================================================
'===================================================================
'To set the constant cell vertical increment for separate pages
adH = 40
k = 0
j = sht.ChartObjects.Count
'===================================================================
Application.PrintCommunication = True 'this will allow page settings to update
'To set page margins, adding some info about the file location, tab name and date
With ActiveSheet.PageSetup
.LeftMargin = Application.InchesToPoints(0.7)
.RightMargin = Application.InchesToPoints(0.7)
.TopMargin = Application.InchesToPoints(0.75)
.BottomMargin = Application.InchesToPoints(0.75)
.HeaderMargin = Application.InchesToPoints(0.3)
.FooterMargin = Application.InchesToPoints(0.3)
.Orientation = xlLandscape
.LeftHeader = "Date generated : " & Now
.CenterHeader = ""
.RightHeader = "File name : " & ActiveWorkbook.Name
.LeftFooter = "File location : " & FilePath & ThisWorkbook.Name
.CenterFooter = ""
.RightFooter = ""
.FitToPagesWide = 1
End With
'===================================================================
'adjusting page layout borders
sht.VPageBreaks.Add sht.[N1]
For i = 40 To j * 40 Step 40
sht.HPageBreaks.Add Before:=sht.Cells(i + 1, 1)
Next i
Columns("A:A").EntireRow.RowHeight = 12.75
Rows("1:1").EntireColumn.ColumnWidth = 8.43
'===================================================================
For i = 1 To j
Set Rng = ActiveSheet.Range("A" & (1 + k * adH) & " :M" & (40 + k * adH) & "")
With ActiveSheet.ChartObjects(i)
.Height = Rng.Height
.Width = Rng.Width
.Top = Rng.Top
.Left = Rng.Left
End With
ActiveSheet.PageSetup.PrintArea = "$A$1:$M" & (40 + k * adH) & ""
k = k + 1
Next i
'===================================================================
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FilePath & ActiveWorkbook.Name & "." & ActiveSheet.Name, Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
'===================================================================
Application.DisplayAlerts = False
ThisWorkbook.Sheets("ALL").Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub