Trying to copy worksheets in multiple pdfs - Syntax Error - excel

Could you kindly help me with this code? I am a beginner..
Sub ExportSheetstoPDF()
Dim ws As Worksheet
Dim mywsname As String
For Each ws In Worksheets
ws.Select
mywsname = ws.Name
Activesheet.ExportAsFixedFormat Type:=xlTypePDF, _
filename:="Z:\Incent_2022\ORDINARIA\RETAIL-WHS\Schede Obiettivi\Q1\" & "Schede Obiettivi Retail Classico Q1 22_" & mywsname & “.pdf”, _
Next ws
End Sub

Your problem is that the line
Activesheet.ExportAsFixedFormat Type:=xlTypePDF, _
filename:="Z:\Incent_2022\ORDINARIA\RETAIL-WHS\Schede Obiettivi\Q1\" & "Schede Obiettivi Retail Classico Q1 22_" & mywsname & “.pdf”, _
has the continuation character _ at the end of it, but nothing continues on the next line.
Remove the ,_ from the end of the line
Also the “.pdf” needs to be ".pdf" i.e. using ordinary double-quotes and not ones copied out of an Office document ("intelligent" double-quotes)

Related

VBA Excel - Export PDF file from Excel with second page

Just want to ask if how can I export a PDF file with vba? The thing is I do have a 10-F and 10-B sheet. The code below is working in the 10-F sheet. My problem is how can I export the data in the 10-B sheet together with the 10-F? The first page is the data in 10-F while the data in 10-B will be on the second page.
The range for the 10-B sheet is "B10:AD92".
Sub Ver_PDF()
'Create and assign variables
Dim saveLocation As String
Dim rng As Range
lname = ThisWorkbook.Sheets("HOME").Range("K12")
fname = ThisWorkbook.Sheets("HOME").Range("K13")
Name = fname & " " & lname
pdfile = "V-" & Name & ".pdf"
saveLocation = ThisWorkbook.Path & "\V-PDF\" & pdfile
Set rng = Sheets("10-F").Range("B9:AD89")
Dim strFileExists As String
strFileExists = Dir(saveLocation)
If strFileExists <> "" Then
Dim Ret
'~~> Change this to the relevant file path and name
Ret = IsFileOpen(saveLocation)
If Ret = True Then
MsgBox "Please close the PDF file before proceeding...", vbCritical + vbOKOnly, "Error"
Exit Sub
End If
End If
rng.ExportAsFixedFormat Type:=xlTypePDF, _
FileName:=saveLocation, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Any help is highly appreciated! Thanks!
This code will do what you want. Change the worksheet names in the array as well as the destination path and file name.
Sub ExportAsPDF()
Dim FolderPath As String
Dim FileName As String
FolderPath = "D:\Test PDFs\" ' change to suit: end on back-slash
FileName = "Test" ' change to suit
On Error Resume Next
MkDir FolderPath
On Error GoTo 0
Worksheets(Array("10-F", "10-B")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
FileName:=FolderPath & FileName & ".PDF", _
OpenAfterPublish:=True, _
IgnorePrintAreas:=False
MsgBox "PDF was successfully created."
Worksheets(1).Select
End Sub
Change OpenAfterPublish to False if you don't want to see the result right away.

How can I remove ws.name

I tried to create a PDF file using following script, it works but when I remove ws.Name, the script breaks.
Sub createPDFfiles()
Dim ws As Worksheet
Dim strName As String
For Each ws In ActiveWorkbook.Worksheets
On Error Resume Next 'Continue if an error occurs
' Name PDF files based on the worksheet Index (e.g Annex 1.1.1, Annex 1.1.2, etc.)
strName = Range("A10").Text & " " & Range("C7").Text & ws.Name
' If you want to name the PDF files differently just change the Fname variable above to
' whatever you like. For example if you changed Fname to:
'
' Fname = "C:\myFolder\pdfs\" & ActiveWorkbook.Name & "-" & ws.Name
'
' The files would be stored in C:\myFolder\pdfs, and named using the
' spreadsheet file name and the worksheet name.
'
' WARNING: Using worksheet names may cause errors if the names contain characters that Windows
' does not accept in file names. See below for a list of characters that you need to avoid.
'
ws.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next ws
End Sub
How can I remove this ws.Name and still work?
Your Range objects are unqualified in this statement:
strName = Range("A10").Text & " " & Range("C7").Text & ws.Name
So they are referring to those cells on the active sheet, rather than on sheet ws.
If you wanted to refer to those cells on each worksheet you loop through, then qualify them appropriately:
strName = ws.Range("A10").Text & " " & ws.Range("C7").Text
You may wish to test that strName is not null before you try to save the PDF.
I'd also recommend losing the On Error Resume Next line, and handling errors properly.

Trying to protect a specific sheet in work book but get 40036 error

I am opening a specific file set as wb, it is reading the sheet thus my msgbox as a check but when I come to protect the same sheet I get the compiler error.
I have tried numerous methods to complete this task but none work, such as activating the specific sheet "Front Page" selecting it etc but to no avail.
Where am I going wrong?
Thanks
Dim Sht As Worksheet
Dim wb As Workbook
Dim LastRow As Long
Dim WSName As String
Dim URNName As String
Dim lRow As Long
Workbooks.Open Filename:= "\\Folder\1718 list of SD(s) trainees.xlsm"
Worksheets("pivot").Activate
LastRow = 240
For i = 4 To 240
WSName = Cells(i, 6)
URNName = Cells(i, 7)
' Workbooks.Open Filename:="\\Folder\Annex G Usage\" & WSName & " " & URNName & " SD(s)17-18 Statement of Grant Usage.xlsm"
Set wb = Workbooks.Open("\\Folder\Annex G Usage\" & WSName & " " & URNName & " SD(s)17-18 Statement of Grant Usage.xlsm")
MsgBox " Name" & Cells(10, 3)
' wb.Sheets("Front Page").Activate
ActiveSheet.Protect Password:="SOReadyToHelp", _
DrawingObjects:=True, _
Contents:=True, _
Scenarios:=True, _
AllowSorting:=True, _
AllowFiltering:=True, _
AllowUsingPivotTables:=True
ActiveWorkbook.Save
ActiveWindow.Close
Next i
End Sub

VBA exits before end

EDIT
I got it to run thru about 1,000 part numbers, but now it stops and excel freezes. Is it possibly too much for excel to handle? Would it be better to add a filter and have user perform this task based off criteria xyz?
I'm using the following code to create a mass form replacement. It's intended to run through a list of 5000+ part numbers, paste the part number into a designated range on another worksheet where it creates the form and saves it as a pdf in a specified folder. It works up until row 105 and then stops. It does what it's supposed to, other than continue down the sheet. I have the same code (modified slightly) being used on another sheet and it runs perfect. I'm not sure why its stopping after a certain number of rows
Private Sub CommandButton2_Click()
Application.ScreenUpdating = False
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
strTime = Format(Now(), "yyyymmdd\_hhmm")
Dim x As Worksheet
Dim y As Worksheet
Dim i As Long
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
For i = 3 To FinalRow
Set x = ThisWorkbook.Worksheets("Part Number Database")
Set y = ThisWorkbook.Worksheets("BOM")
x.Cells(i, 1).Copy Destination:=y.Range("E3:J3")
strFile = Range("E3") & ".pdf"
strPathFile = strPath & strFile
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\AGoodwin\Desktop\BOM\" & strFile & ".pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
Next i
MsgBox "PDF file has been created: " _
& vbCrLf _
& myFile
End Sub

Only save populated spreadsheets with filled in cells as PDF

I'm currently trying to modify a Visual Basic macro to only save spreadsheets in a workbook that have had populated cells.
The current macro just saves the entire 16 sheet workbook as a PDF yet a maximum of 9 of these sheets are sometimes left uncompleted, yet are still saved.
I would like the macro to automatically check if these sheets have been populated, once the 'SAVE' button is clicked and then proceed to only save the filled out (complete) sheets as a PDF.
I would massively appricate any help!
The code below is how the macro currently works when just saving the entire workbook. (There is an IF statement check before it is saved to PDF.)
Sub SaveAsPDF()
With ThisWorkbook.Sheets("COVERPage1PRINT")
If (Len(.Range("C24")) = 0) Then
MsgBox "Ensure Serial Number or Stamp number are filled."
Exit Sub
ElseIf (Len(.Range("H17")) = 0) Then
MsgBox "Ensure Serial Number or Stamp Number are filled."
Exit Sub
Else
ChDir _
"P:\Cells\Spool & Sleeves Cell\Flow Plot Records\EFA\Saved EFA PDF Archive"
fname = Sheets("COVERPage1PRINT").Range("H17")
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"P:\Cells\Spool & Sleeves Cell\Flow Plot Records\EFA\Saved EFA PDF Archive\" & fname, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
End If
End With
End Sub
This should do the job
(edited code)
Sub test1()
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim test() As String
Dim i As Integer
Dim pdfpath As String
Dim sheets_to_be_checked() As Variant
Dim a As Boolean
pdfpath = ActiveWorkbook.Path 'YOU CAN ADD YOUR PDF SAVING LOCATION e.g. "C\Users\ABC\Desktop"
i = 0
sheets_to_be_checked = Array("Sheet1", "Sheet3")
Set wbBook = ActiveWorkbook
With ThisWorkbook.Sheets("COVERPage1PRINT")
If (Len(.Range("C24")) = 0) Then
MsgBox "Ensure Serial Number & Tag Number or Stamp number are filled."
Exit Sub
ElseIf (Len(.Range("H16")) = 0) Then
MsgBox "Ensure Serial Number & Tag Number or Stamp Number are filled."
Exit Sub
ElseIf (Len(.Range("H19")) = 0) Then
MsgBox "Ensure Serial Number & Tag Number or Stamp Number are filled."
Exit Sub
Else:
For Each wsSheet In wbBook.Worksheets
With wsSheet
If IsInArray(wsSheet.Name, sheets_to_be_checked) Then
wsSheet.Activate
If WorksheetFunction.CountA(Range("D4:D9, E10:E15, F4:F9, G10:G15, H4:H9, I10:I15, J4:J9, K10:K15")) = 48 Then
ReDim Preserve test(i)
test(i) = wsSheet.Name
i = i + 1
End If
Else:
ReDim Preserve test(i)
test(i) = wsSheet.Name
i = i + 1
End If
End With
Next wsSheet
End If
End With
ThisWorkbook.Sheets(test()).Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=pdfpath & "\ouput.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
The answer might change a little depending on your definition of populated sheets. You would have to alter the condition "If .UsedRange.Address <> "$A$1" Then "
One possible alternative to above is WorksheetFunction.CountA(Range("A1:Z100")) <> 0
Please let me know if you need any assistance with the condition or the code.
This is going to depend somewhat on what exactly you mean by 'automatically check if these sheets have been populated'. My crystal ball says that each worksheet has a header row and would be considered 'populated' if there was any data below the first row. In that case, you could cycle through all worksheets and construct an array of worksheet names to be selected. Once multiple worksheets are selected, the PDF creation would be on ActiveSheet.ExportAsFixedFormat not ActiveWorkbook.ExportAsFixedFormat and only those worksheets selected would be included in the PDF.
Dim w As Long, sWSs As String, vWSs As Variant
For w = 1 To Sheets.count
With Sheets(w)
If .Cells(1, 1).CurrentRegion.Rows.count > 1 Then _
sWSs = sWSs & .Name & Chr(215)
End With
Next w
If CBool(Len(sWSs)) Then
vWSs = Split(Left(sWSs, Len(sWSs) - 1), Chr(215))
Sheets(vWSs).Select
ChDir _
"P:\Cells\Spool & Sleeves Cell\Flow Plot Records\EFA\Saved EFA PDF Archive"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"P:\Cells\Spool & Sleeves Cell\Flow Plot Records\EFA\Saved EFA PDF Archive\" & fname, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
Else
MsgBox "Nothing to publish to PDF."
End If
I've tested this with my own sample workbook then tried to incorporate your code sample specifics into my method. If it doesn't work the first time post back a comment and I may be able to offer assistance.

Resources