Multiple excel worksheets to PDF - vba

All,
I have the below code which copies multiple worksheets in excel and exports them to a PDF worksheet. One worksheet per PDF page, I would like to know if it is possible to have two worksheets on one PDF page as the current VBA code leaves a lot of blank spaces within the PDF file.
**On each worksheet I have set the print area which is not a variable, So I'm assuming if there is a code to copy the print areas on selected sheets this would work perfectly.
Sub print_test()
Dim strPath As String, strFileName As String
ThisWorkbook.Sheets(Array("Metadata", "BC on a page", "Approvals", "RMIB")).Select
'Select file save location
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
strPath = .SelectedItems(1)
End If
End With
strFileName = InputBox("Please input filename", "Filename")
strPath = strPath & "\"
strFileName = strFileName & ".pdf"
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strPath & strFileName, _
IgnorePrintAreas:=False
Sheets("Metadata").Select
End Sub

Related

VBA to open file exported Excel file in PDF XChange Viewer

Hi guys i'm brand new to coding but i have somehow (haha) managed to export my excel into PDF. Now Im having difficulties trying to have the PDF automatically open in PDF XChange Viewer instead of Adobe Reader.
Here are my codes:
Sub Export()
Dim wsA As Worksheet
Dim wsB As Workbook
Dim strPath As String
Dim myFile As Variant
Set wbA = ActiveWorkbook
Set wsA = ActiveWorksheey
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
myFile = Application.GetSaveAsFilename _
(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:=True
End If
End Sub
Disclaimer i copied the codes from somewhere online because i wanted to allow users to name the file, select where they save it.
What should i do to open the PDF in PDFXChange Viewer. The directory is: C:\Program Files\Tracker Software\PDF Viewer
As you mentioned you already managed to export to PDF, so try below code to open the PDF file in Adobe Reader In case of PDF XChange Viewer put XChange Viewer exe file path in the code.
Sub OpenPDFbyAdobeReader()
Dim exePath, filePath As String
Dim OpenFile
exePath = "C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe"
filePath = "E:\CyberArk\DNA_Datasheet.pdf"
openPath = exePath & " " & filePath
OpenFile = Shell(openPath, vbNormalFocus)
End Sub
Edit
Sub to save as pdf then open in a program.
Sub Export()
Dim wsA As Worksheet
Dim wsB As Workbook
Dim strPath As String
Dim myFile As Variant
Dim appPath As String
Dim OpenFile
Set wbA = ActiveWorkbook
Set wsA = ActiveWorkbook.ActiveSheet
appPath = "C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe"
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
myFile = Application.GetSaveAsFilename _
(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
OpenFile = Shell(appPath & " " & myFile, vbNormalFocus)
End If
End Sub
You have to replace appPath with your XChange viewer path.
Open PDF in PDFXCview
Below is an example of how to call the application using Shell. You'd need to specify the path/filename of your PDF, and you may need to confirm the location of PDFXCview.exe on your machine.
Sub OpenPDF_test()
Const XCviewPath = "C:\Program Files\Tracker Software\PDF Editor\PDFXCview.exe"
Const pdfFileName = "C:\myPath\myPDFfileName.pdf"
Debug.Print XCviewPath & " """ & pdfFileName & """"
End Sub
PDFXCview.exe Command Line Options
You can also add command line options if you want to automate more advanced tasks.
For example, you could have it:
automatically print and then close the file,
hide the user interface,
import saved settings,
or even run custom JavaScript.
Command Line switches
/A "param=value [&param2=value [&...]"
/close[:save|discard|ask]
/print[:[default=yes|no][&showui=yes|no][&printer=<printername>][&pages=<pagesrange>]]
/printto[:[default=yes|no][&showui=yes|no][&pages=<pagesrange>]] <printername>
/exportp <setting_file_name>
/importp <setting_file_name>
/RegServer
/UnregServer
/usep <setting_file_name>
More Information Here.

BeforePrint Event is Firing without Printing

I have the code below. It makes me wonder why the BeforePrint event in the workbook codes is fired even though I am not printing anything. The workbook definitely is not blank. The error is in the creation of the PDF file.
The file does a simple job of saving the worksheet in a PDF format with the name of the sheet, the file path of the workbook, and some details inside the worksheet.
Anything that I am missing? I am not new to VBA but this bugs me a lot today. I am using MS Excel 2016 on Windows 7 ultimate.
Edit: I tried removing the following codes below but the problem still persists:
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
The code is as follows:
Option Explicit
Public Sub createpdffile()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Dim sheetname As String, sheetcode As String
Dim iRow As Long
Dim openPos As Integer
Dim closePos As Integer
'temporarily disable error handler so that I can see where the bug is.
'On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
wbA.Save
'get last row of sheet and set print area to last row with L column
iRow = wsA.Cells(Rows.Count, 1).End(xlUp).Row
wsA.PageSetup.PrintArea = wsA.Range("A1:L" & iRow).Address
'just checking name in sheet and removing needed characters
sheetname = wsA.Name
openPos = InStr(sheetname, "(")
closePos = InStr(sheetname, ")")
sheetcode = Mid(sheetname, openPos + 1, closePos - openPos - 1)
'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
'create default name for saving file
strFile = sheetcode & " No. " & wsA.Cells(11, 9) & " - " & wsA.Cells(8, 3) & ".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
'THIS IS WHERE THE ERROR IS LOCATED
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
'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" & vbNewLine & _
"Please complete the details needed!", vbOKOnly + vbExclamation, "Error Saving as PDF"
Resume exitHandler
End Sub
Solution from Foxfire and Burns and Burns' idea:
I added a public declaration before the main sub.
Option Explicit
'added line
Public myboolean as Boolean
Public Sub createpdffile()
myboolean = True
....
Then I added a line in the BeforePrint Event that says:
If myboolean = True Then Exit Sub
This now bypasses the BeforePrint event when the virtual PDF printer is called.
wsA.ExportAsFixedFormat
That line activates the BeforePrint Event. Actually, you are printing a PDF file. It works as a virtual PDF Printer.

Excel VBA Convert .csv to Excel File

I have a folder which has .csv files, .xls files, and xlsx files. The below code is a portion of an overall project (when I remove the below code, the remaining code achieves what I want). A large chunk of the code was compiled from somewhere (here and around the internet). What I want the code to do is open only the .csv files in the folder, convert them to an Excel file, close the files, and then delete the .csv files in the folder. What ends up happening with the code is that one or both of the files created by the code are deleted from the folder, and I am left with nothing. Thanks in advance for any help.
Sub Test()
'
' Test Macro
'
'Set variables for the below loop
Dim MyFolder As String
Dim MyFile As String
Dim GetBook As String
Dim GetBook2 As String
Dim MyCSVFile As String
Dim KillFile As String
MyFolder = "REDACTED"
MyFile = Dir(MyFolder & "\*.xls")
MyCSVFile = Dir(MyFolder & "\*.csv")
'Open all of the .csv files in the folder and convert to .xls
Do While MyCSVFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyCSVFile
GetBook = ActiveWorkbook.Name
GetBook2 = Left(GetBook, Len(GetBook) - 4)
ActiveSheet.Name = "Sheet1"
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=GetBook2, FileFormat:=56
ActiveWorkbook.Close False
Kill MyFolder & "\" & GetBook
Loop
End Sub
You are not calling the Dir function to get the next file.
Sub Test()
'Set variables for the below loop
Dim myFolder As String
Dim getBook As String
Dim myCSVFile As String
Application.DisplayAlerts = False
myFolder = Environ("TEMP") & Chr(92) & "REDACTED"
myCSVFile = Dir(myFolder & "\*.csv")
Do While myCSVFile <> ""
Workbooks.Open Filename:=myFolder & "\" & myCSVFile
getBook = ActiveSheet.Name '<~ Sheet1 of an opened CSV is the name of the CSV
ActiveSheet.Name = "Sheet1"
ActiveWorkbook.SaveAs Filename:=myFolder & Chr(92) & getBook, FileFormat:=56
ActiveWorkbook.Close False
Kill myFolder & Chr(92) & myCSVFile '<~~ delete the CSV, not the workbook
myCSVFile = Dir '<~~ this is important to get the next file in the folder listing
Loop
End Sub
The only worksheet in an opened CSV is named for the CSV (without the .CSV extension) so that can be used in the Workbook.SaveAs method. I've used xlOpenXMLWorkbook as the SaveAs FileFormat type.

Selecting Where PDF Files Save

I'm so relieved that I finally got the code below to work with the help of this community.
I have one more option on my wishlist that I'm struggling with. Currently, the code below will save worksheet 3 all the way to worksheet titled "post" as separate PDF files into a folder I select. This is triggered by a shape.
I'm trying to make the below code prompt a folder select so users can select where their PDF files are saved, does anyone have any ideas how to do this?
Also, the Call Shell at the bottom would preferably open the folder where the files are saved, but that's not really necessary as long as users know where the files are being saved :)
Sub SaveAllPDF()
Dim i As Integer
Dim Fname As String
Dim TabCount As Long
TabCount = Sheets("Post").Index
'Set the TabCount to the last cell you want to PDF
' Begin the loop.
For i = 3 To TabCount
'Set i = the number of the first sheet you want to PDF in order from left to right To TabCount
If Sheets(i).Visible <> xlSheetVisible Then
Else
With Sheets(i)
Fname = .Range("C15") & " " & .Range("E13") & "-" & .Range("B1")
'The Fname above is equaling the cells that the PDF's filename will be
'The folder directory below is where the PDF files will be saved
.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\Brandon\Desktop\operation automated\RLtemp\" & Fname, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
End If
Next i
Call Shell("explorer.exe" & " " & "C:\Users\Brandon\Desktop\operation automated\RLtemp\", vbNormalFocus)
'This opens the folder where the PDFs are saved
End Sub
You can just use the Excel's FileDialog object:
Sub SaveAllPDF()
Dim i As Integer
Dim Fname As String
Dim TabCount As Long
TabCount = Sheets("Post").index
'Set the TabCount to the last cell you want to PDF
Dim dialog As FileDialog
Dim path As String
Set dialog = Application.FileDialog(msoFileDialogFolderPicker)
dialog.AllowMultiSelect = False
If dialog.Show = -1 Then
path = dialog.SelectedItems(1)
' Begin the loop.
For i = 3 To TabCount
'Set i = the number of the first sheet you want to PDF in order from left to right To TabCount
If Sheets(i).Visible <> xlSheetVisible Then
Else
With Sheets(i)
Fname = .Range("C15") & " " & .Range("E13") & "-" & .Range("B1")
'The Fname above is equaling the cells that the PDF's filename will be
'The folder directory below is where the PDF files will be saved
.ExportAsFixedFormat Type:=xlTypePDF, filename:=path & "\" & Fname, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
End If
Next i
Call Shell("explorer.exe" & " " & path & "\", vbNormalFocus)
'This opens the folder where the PDFs are saved
End If
End Sub

Excel VBA Open a Folder

Using 2010 Excel VBA - I'm just trying to open a folder through a sub. What am I doing wrong here?
VBA
Sub openFolder()
Dim preFolder As String, theFolder As String, fullPath as String
theFolder = Left(Range("T12").Value, 8)
preFolder = Left(Range("T12").Value, 5) & "xxx"
fullPath = "P:\Engineering\031 Electronic Job Folders\" & preFolder & "\" & theFolder
Shell(theFolder, "P:\Engineering\031 Electronic Job Folders\" & preFolder, vbNormalFocus)
End Sub
If you want to open a windows file explorer, you should call explorer.exe
Call Shell("explorer.exe" & " " & "P:\Engineering", vbNormalFocus)
Equivalent syxntax
Shell "explorer.exe" & " " & "P:\Engineering", vbNormalFocus
I use this to open a workbook and then copy that workbook's data to the template.
Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
.Filters.Clear
.Title = "Your Title"
If Not .Show Then
MsgBox "No file selected.": Exit Sub
End If
Workbooks.OpenText .SelectedItems(1)
'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1
Set myfile = ActiveWorkbook
ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
myfile.Close
Template.Activate
ActiveSheet.Cells.Select
Selection.Copy
Sheets("Sheet1").Select
Cells.Select
ActiveSheet.Paste
End With