Excel VBA: Delete sheet after exporting to PDF - excel

I have written the following code tied to a command button to prompt the user to define a save path, export the active sheet to PDF and open it, then delete the sheet after it's been exported and activate a different sheet. The code works to completion but right at the end, I get a the following error:
Run-time error '-2147221080 (800401a8)':
Automation error
Below is my code. Any help would be immensely appreciated.
Private Sub ExceptionPrint_Click()
Sheet_Name = ActiveSheet.Name
PDF_Name = "Exception - " & ActiveSheet.Name & ".pdf"
Set File_Dialog = Application.FileDialog(msoFileDialogFolderPicker)
File_Dialog.AllowMultiSelect = False
File_Dialog.Title = "Select the Desired Location"
If File_Dialog.Show <> -1 Then
Exit Sub
End If
PDF_Name = File_Dialog.SelectedItems(1) & "\" & PDF_Name
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=PDF_Name, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
If Sheets("Data").Range("H12").Value = "W1" Then
Sheets("Week 1").Activate
Sheets("Data").Range("H12").Value = ""
Else
Sheets("Week 1").Activate
Sheets("Data").Range("H12").Value = ""
End If
Application.DisplayAlerts = False
Sheets(Sheet_Name).Delete
Application.DisplayAlerts = True
End Sub
I've tried everything I could think of, but I'm not that great with VBA to begin with.

Assign the active sheet to a reference at the start and use that reference throughout the program. Also try to catch early any errors that the user might make.
Option Explicit
Private Sub ExceptionPrint_Click()
Dim wb As Workbook, wsPDF As Worksheet, PDF_Name As String
' validation
Set wb = ThisWorkbook
Set wsPDF = wb.ActiveSheet
With wsPDF
If .Name = "Week 1" Or .Name = "Data" Then
MsgBox "Sheet " & wsPDF.Name & " must not be selected", vbCritical
Exit Sub
ElseIf WorksheetFunction.CountA(.UsedRange) = 0 Then
MsgBox .Name & " is blank", vbCritical
Exit Sub
End If
End With
' select folder
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Title = "Select the Desired Location"
If .Show <> -1 Then Exit Sub
PDF_Name = .SelectedItems(1) & "\Exception - " & wsPDF.Name & ".pdf"
End With
' print and delete
wsPDF.ExportAsFixedFormat Filename:=PDF_Name, Type:=xlTypePDF, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=True
Application.DisplayAlerts = False
wsPDF.Delete
Application.DisplayAlerts = True
' finish
With wb
.Sheets("Week 1").Activate
.Sheets("Data").Range("H12").Value = ""
End With
End Sub

I ended up just leaving a "Delete Sheet" button on the sheet in question rather than having it automatically delete. Thank you everyone.

Related

VBA print line number and column letter in pdf document

So I am trying to print an Excel sheet. So far I got most of the stuff set up, but I can't get the line number nor the column letter working.
I tried a bunch of stuff like LineNumbering, PrintTitleColumns, but I think that's not what I am actually looking for.
Here's my code:
Sub PrintToPDF()
' Saves active sheet as PDF file.
Dim Name As String
Dim wkPrint As Worksheet
FileNameArray = Split(ThisWorkbook.Name, ".")
Name = ThisWorkbook.Path & "\" & Format(Now(), "yyyy-mm-dd") & "_" & FileNameArray(0) & ".pdf"
Set wkPrint = ThisWorkbook.Worksheets("Dokumentation")
'On Error GoTo err
'wkPrint.PrintCommunication = True
With wkPrint.PageSetup
.PaperSize = xlPaperA3
.RightHeader = "&D &T"
.PrintGridlines = True
'.LineNumbering.Active = True
'.PrintTitleColumns = "A:AA"
End With
'Application.PrintCommunication = True
wkPrint.ExportAsFixedFormat Type:=xlTypePDF, Filename:=Name, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Exit Sub
'err:
'MsgBox err.Description
End Sub
Thanks in advance!
You are looking for wkPrint.PageSetup.PrintHeadings = True

Excel How To Get Values From Another Excel with Fullpath?

I want to copy the data from a closed file I have selected and see it in the file containing this macro.
I am using Office365.
How can i copy data from this "FullPath" workbook ?
Private Sub PathName()
Dim FullPath As String
On Error GoTo extApp
FullPath = Application.GetOpenFilename(FileFilter:="File Filter," & _
"*.xls;*.doc;*.xlsx;*.mdb;*.ppt;*.pdf", Title:="Please Select A File")
Exit Sub
extApp: Select Case Err.Number
Case 104
MsgBox ("104")
Exit Sub
Case Else
MsgBox "Runtime Error: " & Err.Number & vbNewLine & Err.Description
Stop
Resume
End Select
End Sub
You may try the following code modication, add in your other part of code to make it work as a complete sub:
Private Sub PathName()
Dim FullPath As String
Dim wb As Workbook
Application.DisplayAlerts = False
On Error GoTo extApp
FullPath = Application.GetOpenFilename(FileFilter:="File Filter," & _
"*.xls;*.doc;*.xlsx;*.mdb;*.ppt;*.pdf", Title:="Please Select A File")
Set wb = Workbooks.Open(FullPath, , True)
wb.Worksheets("Sheet1").Range("A1:B" & lastrow).Copy
Sheet1.Range("A1").PasteSpecial xlPasteValues
'
'
'
wb.Close
Application.DisplayAlerts = True
End Sub

Excel VBA for Switching Style on and off on user selected page in a locked database

I have a database where the user can select one of 17 different pages. Once the page is selected, I need to highlight the part of the page where the user can enter data (switch Style on). Once the user has completed entering the data, the form is then converted to pdf and sent as an attachment in an email, and the style needs to be switched off before the conversion starts.
First, I have this code set when the workbook opens
Private Sub Workbook_Open()
Rem Using Sheet instead of Worksheet to care for Charts in the workbook if any
Dim Sht As Object
'Prevent Computer Screen from running
Application.ScreenUpdating = False
With ThisWorkbook
For Each Sht In .Sheets
With Sht
.Unprotect Password:="Password"
End With: Next
With .Sheets("Menu")
Activate
Application.Goto .Cells(1), 1
End With: End With
With ThisWorkbook
For Each Sht In .Sheets
With Sht
.Protect Password:="Password", _
DrawingObjects:=True, Contents:=True, _
Scenarios:=True, UserInterFaceOnly:=True
End With: Next
End With
InputStyleRestore
'Allow Computer Screen to refresh
Application.ScreenUpdating = True
End Sub
This leads to the sub routine InputStyleRestore
Sub InputStyleRestore()
'Prevent Computer Screen from running
Application.ScreenUpdating = False
With ThisWorkbook
For Each Sht In .Sheets
Sht.Unprotect Password:="Password"
Next: End With
With ActiveWorkbook.Styles("Input")
.Interior.Color = 10079487
.Font.Color = -9027777
End With
With ThisWorkbook
For Each Sht In .Sheets
With Sht
.Protect Password:="Password", _
DrawingObjects:=True, Contents:=True, _
Scenarios:=True, UserInterFaceOnly:=True
End With: Next: End With
'Allow Computer Screen to refresh
Application.ScreenUpdating = True
End Sub
Now I have a routine where depending on which page the user selects creates a specific form into a pdf and email
Sub PartialPrintFamForm()
Dim FTW As Long
Dim myVariable As String
Dim IsCreated As Boolean
Dim i As Long
Dim PdfFile As String, Title As String
Dim OutlApp As Object
' Employee Name as Title
Title = Range("E21")
If ActiveSheet.Name = "Caledonian Road Fam Form" Then
myVariable = Sheets("Caledonian Road Fam Form").Range("R21").Value
Sheets("Data Input").Range("B1310").Value = WorksheetFunction.Match(Sheets("Caledonian Road Fam Form").Range("O21").Value, Sheets("Data Input").Range("B1:B1000"), 0)
FTW = Sheets("Data Input").Range("B1310").Value
Sheets("Data Input").Cells(FTW, 25) = myVariable
MsgBox "The First page only will now print out for you."
InputStyleClear
' Define PDF filename
PdfFile = ActiveWorkbook.FullName
i = InStrRev(PdfFile, ".")
If i > 1 Then PdfFile = Left(PdfFile, i - 1)
PdfFile = PdfFile & "_" & ActiveSheet.Name & ".pdf"
' Export activesheet as PDF
With ActiveSheet.Range("A1:T33")
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
' Use already open Outlook if possible
On Error Resume Next
Set OutlApp = GetObject(, "Outlook.Application")
If Err Then
Set OutlApp = CreateObject("Outlook.Application")
IsCreated = True
End If
OutlApp.Visible = True
On Error GoTo 0
' Prepare e-mail with PDF attachment
With OutlApp.CreateItem(0)
' Prepare e-mail
.Subject = "Familiarisation Certificate for " & Title
.To = "Name#Domain.uk" ' <-- Put email of the recipient here
.CC = "Name#Domain.uk" ' <-- Put email of 'copy to' recipient here
.Body = "Hi," & vbLf & vbLf _
& "The Familiarisation report is attached in PDF format." & vbLf & vbLf _
& "Regards," & vbLf _
& Application.UserName & vbLf & vbLf
.Attachments.Add PdfFile
.Display
' Try to send
On Error Resume Next
'.Send
Application.Visible = True
If Err Then
MsgBox "E-mail was not sent", vbExclamation
Else
MsgBox "E-mail successfully sent", vbInformation
End If
On Error GoTo 0
End With
' Delete PDF file
Kill PdfFile
' Release the memory of object variable
Set OutlApp = Nothing
ActiveSheet.Range("A1:T33").PrintOut
Range("O21,O28").ClearContents
End If
If ActiveSheet.Name = "Arsenal Fam Form" Then
myVariable = Sheets("Arsenal Fam Form").Range("R21").Value
Sheets("Data Input").Range("B1310").Value = WorksheetFunction.Match(Sheets("Arsenal Fam Form").Range("O21").Value, Sheets("Data Input").Range("B1:B1000"), 0)
FTW = Sheets("Data Input").Range("B1310").Value
Sheets("Data Input").Cells(FTW, 9) = myVariable
MsgBox "The First page only would print, but has temporarily been disabled during testing."
InputStyleClear
' Define PDF filename
PdfFile = ActiveWorkbook.FullName
i = InStrRev(PdfFile, ".")
If i > 1 Then PdfFile = Left(PdfFile, i - 1)
PdfFile = PdfFile & "_" & ActiveSheet.Name & ".pdf"
' Export activesheet as PDF
With ActiveSheet.Range("A1:T33")
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
' Use already open Outlook if possible
On Error Resume Next
Set OutlApp = GetObject(, "Outlook.Application")
If Err Then
Set OutlApp = CreateObject("Outlook.Application")
IsCreated = True
End If
OutlApp.Visible = True
On Error GoTo 0
' Prepare e-mail with PDF attachment
With OutlApp.CreateItem(0)
' Prepare e-mail
.Subject = "Familiarisation Certificate for " & Title
.To = "Name#Domain.uk" ' <-- Put email of the recipient here
.CC = "Name#Domain.uk" ' <-- Put email of 'copy to' recipient here
.Body = "Hi," & vbLf & vbLf _
& "The report is attached in PDF format." & vbLf & vbLf _
& "Regards," & vbLf _
& Application.UserName & vbLf & vbLf
.Attachments.Add PdfFile
.Display
' Try to send
On Error Resume Next
'.Send
Application.Visible = True
If Err Then
MsgBox "E-mail was not sent", vbExclamation
Else
MsgBox "E-mail successfully sent", vbInformation
End If
On Error GoTo 0
End With
' Delete PDF file
Kill PdfFile
' Release the memory of object variable
Set OutlApp = Nothing
ActiveSheet.Range("A1:T33").PrintOut
Range("O21,O28").ClearContents
End If
InputStyleRestore
Sheets("Familiarisation").Select
ThisWorkbook.Save
End Sub
I am trying to get InputStyleClear to clear just the active page that has been selected. If I use the same routine as InputStyleRestore to clear the Style, I find that the page that is converted to pdf & email is always the very last page in the workbook, and not the page originally selected. I tried to see if I could just get InputStyleClear to clear the active page with this code
Sub InputStyleClear()
'Prevent Computer Screen from running
Application.ScreenUpdating = False
With ActiveSheet.Name
.Unprotect Password:="Password", _
DrawingObjects:=False, Contents:=False, _
Scenarios:=False, UserInterFaceOnly:=False
End With
With ActiveSheet.Styles("Input")
.Interior.Pattern = xlNone
.Font.ColorIndex = xlAutomatic
.Borders(xlLeft).LineStyle = xlNone
.Borders(xlRight).LineStyle = xlNone
.Borders(xlTop).LineStyle = xlNone
.Borders(xlBottom).LineStyle = xlNone
End With
With ActiveSheet.Name
.Protect Password:="Password", _
DrawingObjects:=True, Contents:=True, _
Scenarios:=True, UserInterFaceOnly:=True
End With
'Allow Computer Screen to refresh
Application.ScreenUpdating = True
End Sub
but it crashes on line .Interior.Pattern = xlNone. It seems that the InputStyleClear routine works when run on a loop to clear all pages ending up with showing the wrong page, but will not work if trying to unlock a single active page. Any ideas how to achieve what I am looking for would be greatly appreciated.
I suggest to create two Styles and apply each as required before and after printing the PDF's. This will eliminate the need to modify the Workbook Styles and protect and unprotect the worksheets.
Also replace ActiveSheet with object variables:
Dim Wsh As Worksheet
Set Wsh = ThisWorkbook.Sheets("Caledonian Road Fam Form")
Suggest to name the Styles something like "Users" and "UsersPdf"
"UsersPdf" to be applied before printing the PDF's
Wsh.Range("O20,P20,O28,P28").Style = "UsersPdf"
"Users" to be applied after printing the PDF's
Wsh.Range("O20,P20,O28,P28").Style = "Users"

Pivot Slicer Items to PDF - via file dialog folder picker

Hi all and thank you for taking the time to read.
In relation to the code below (code provided by M--) from this post VBA to select each slicer item AND then save each selected slicer item as a pdf?
Rather than a predetermined save / export location i would like the user to select a folder of their choice.
I have been politely informed in stack chat by #QHarr that i need a filedialog object to introduce this function. Would this be at the beginning of the module? Is export better than save.as in this scenario? Would the latter effect the way the slicer items are transferred?
Much appreciated and kind regards
wAnd
Public Sub myMacro()
Dim sC As SlicerCache
Set sC = ActiveWorkbook.SlicerCaches("Slicer_Store_Number")
'This reminds the user to only select the first slicer item
If sC.VisibleSlicerItems.Count <> 1 Or sC.SlicerItems(1).Selected = False Then
MsgBox "Please Only Select Store-Number 1"
Exit Sub
End If
For i = 1 To sC.SlicerItems.Count
'Do not clear ilter as it causes to select all of the items (sC.ClearManualFilter)
sC.SlicerItems(i).Selected = True
If i <> 1 Then sC.SlicerItems(i - 1).Selected = False
'Debug.Print sI.Name
'add export to PDF code here
With Sheet18.PageSetup
.PrintArea = Sheet18.Range("A1:N34" & lastRow).Address
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
Sheet18.Range("M1") = sC.SlicerItems(i).Name
'This prints to C directory, change the path as you wish
Sheet18.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\" & Range("M1").Text & ".pdf", Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next
End Sub
After looking around i have managed to solve it. In a nutshell i didnt use the back slash for Filename:=path & \ & Range("G2").Text
Final code below
Private Sub CommandButton1_Click()
Dim sC As SlicerCache
Set sC = ActiveWorkbook.SlicerCaches("Slicer_Site_Product")
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)
'This reminds the user to only select the first slicer item
If sC.VisibleSlicerItems.Count <> 1 Or sC.SlicerItems(1).Selected = False Then
MsgBox "Please select the top most item"
Exit Sub
End If
For i = 1 To sC.SlicerItems.Count
'Do not clear ilter as it causes to select all of the items (sC.ClearManualFilter)
sC.SlicerItems(i).Selected = True
If i <> 1 Then sC.SlicerItems(i - 1).Selected = False
'Debug.Print sI.Name
'add export to PDF code here
With Sheet5.PageSetup
.PrintArea = Sheet5.Range("B2:M76" & lastRow).Address
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
Sheet5.Range("G2") = sC.SlicerItems(i).Name
For Each CL In Sheet5.Range("M11:M67")
If CL.WrapText Then CL.Rows.AutoFit
Sheet5.Range("A1:A74").AutoFilter Field:=1, Criteria1:=Sheet5.Range("A2")
Next
'This prints to C directory, change the path as you wish
Sheet5.ExportAsFixedFormat Type:=xlTypePDF, Filename:=path & "\" & Range("G2").Text, Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next
End If
End Sub

VBA error 1004 during print PDF

I have this code:
Sub PrintPDF()
Dim wsReport As Worksheet
Dim confirm As Long
Dim filename, reportsPath As String
Dim printArea As Range
Set wsReport = ThisWorkbook.Worksheets("Test Status")
Set printArea = wsReport.Range("A1:AG80")
'Generate Reports folder path
'reportsPath = ThisWorkbook.Path & "\Reports\"
reportsPath = "C:\"
'Generate filename to be printed
Dim LValue As String
LValue = Format(Date, "yyyymmdd")
fp = reportsPath & Range("Project!clientName").Value & "_TestReport_" & LValue & ".pdf"
'Confirm or Cancel the action
confirm = MsgBox("the Test execution report (" & fp & ") will be printed as PDF in the folder " & reportsPath & " .", vbOKCancel + vbQuestion, "Printing Test report")
If confirm = vbCancel Then
Exit Sub
End If
'Set page orientation to landscape
wsReport.PageSetup.Orientation = xlLandscape
'wsReport.PageSetup.Orientation = xlPortrait
Application.ScreenUpdating = False
With ActiveSheet.PageSetup
.printArea = Worksheets("Test Status").UsedRange
'.printArea = wsReport.UsedRange
'.printArea = Worksheets("Test Status").UsedRange
.Orientation = xlLandscape
.FitToPagesWide = 1
.Zoom = False 'I have added this line
End With
printArea.ExportAsFixedFormat Type:=xlTypePDF, filename:=fp, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
This code is activated when the button on the sheet is pressed.
Once I press the button, I got the message box with the filename and path where the file will be stored.
once pressed on "OK" button I got this error:
Run-Time Error '1004' Document not saved. The document may be open or
an error may have been encountered
I'm using Office 365
fixed,
seems that the issue was caused by directory grant.
Btw, I changed the reportsPath
reportsPath = ThisWorkbook.Path & "\Reports\"
And I've added the check to create the directory in case it doesn't exist.
reportsPath = ThisWorkbook.Path & "\Reports\"
If Dir(reportsPath, vbDirectory) = "" Then
create = MsgBox("The Directory " & reportsPath & " doesn't exist. ", vbOKCancel + vbQuestion, "Do you want to create it?")
If create = vbCancel Then
Exit Sub
End If
MkDir reportsPath
Stop
End If
Now it works, no runtime error anymore.

Resources