'Generate PDF of variable number of sheets in an array
I want to send a pdf by email.
The sheets of Excel are variable (from time to time some are added and others removed) and its name is stored in a range of other sheet called Projetos.
My code seems to be working until I try to select my sheets (using an Array).
I get
Run.time error 9 - Subscript out of range.
However if I introduce the sheet name manually in the Array the code does everything perfectly.
Sub Send_PDF_Email()
Dim wPath As String, wFile As String, pets As Variant, myArray As Variant, yourArray As String
R = 5
Do While Not IsEmpty(Sheets("Projetos").Cells(R, 2))
R = R + 1
Exit Do
Loop
pets = Worksheets("Projetos").Range("B5:B" & R).Value
myArray = Application.Transpose(pets)
yourArray = Join(myArray, " , ")
ThisWorkbook.Sheets(yourArray).Select
'ThisWorkbook.Sheets(Array("2070507", "2070614")).Select
wPath = ThisWorkbook.Path
wFile = "DadosRPO.pdf"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=wPath & wFile, Quality:=xlQualityStandard, IncludeDocProperties:=False, IgnorePrintAreas:=False, OpenAfterPublish:=False
On Error GoTo 0
Set dam = CreateObject("Outlook.Application").CreateItem(0)
dam.To = Sheets("Projetos").Cells(28, 3).Value
dam.Subject = "Dados RPO"
dam.Body = "Seguem os dados referentes aos projectos em execução"
dam.Attachments.Add wPath & wFile
dam.Send
End Sub
Solution 1:[1]
Thank you both. I was finally able to run my code properly.
Sub Send_PDF_Email()
Dim wPath As String, wFile As String, myArray() As String
'################ SHEETS TO PDF #######################
R = 5
Do While Not IsEmpty(Sheets("Projetos").Cells(R, 2))
R = R + 1
Loop
cpt = 0
ReDim myArray(1 To R - 5)
For x = 5 To R - 1
cpt = cpt + 1
myArray(cpt) = Worksheets("Projetos").Range("B" & x).Value
Next x
'##################### PDF ################
ThisWorkbook.Sheets(myArray).Select
wPath = ThisWorkbook.Path
wFile = "DadosRPO.pdf"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=wPath & wFile,
Quality:=xlQualityStandard, IncludeDocProperties:=False,
IgnorePrintAreas:=False, OpenAfterPublish:=False
On Error GoTo 0
'#################### EMAIL ####################
Set dam = CreateObject("Outlook.Application").CreateItem(0)
dam.To = Sheets("Projetos").Cells(28, 3).Value
dam.Subject = "Dados RPO"
dam.Body = "Seguem os dados referentes aos projectos em execu??o"
dam.Attachments.Add wPath & wFile
dam.Send
Worksheets("Projetos").Activate
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ruben Ramalhais |
