I have the following problem, in my VBA code it comes to Runtime Error 5 Invalid Procedure call or argument when I want to save a range as PDF. The code looks like this:
Worksheets(2).Range("A1:G103").ExportAsFixedFormat Type:=xlTypePDF, Filename:=path1_1 & "\Idea" & Worksheets(3).Range("B12").Value & ".pdf", OpenAfterPublish:=False
The sheet that is being accessed is hidden. The error message does not occur if Worksheets(2).Visible = True
. How can I write the code so that the error message no longer comes up and I don't have to show the sheets? It would also be good to know why the error occurs. I really appreciate your help.
Worksheets(2).Visible = True
Worksheets(2).Range("A1:G103").ExportAsFixedFormat Type:=xlTypePDF, Filename:=path1_1 & "\Idea" & Worksheets(3).Range("B12").Value & ".pdf", OpenAfterPublish:=False
Worksheets(2).Visible = xlVeryHidden
This is how the VBA code would work but unfortunately this is not an option.
There is no way to use ExportAsFixedFormat
on a hidden sheet (however the Microsoft doesn't tell about the fact or why this is). So if you want to export the sheet, there is no alternative to make it visible temporarily. However, you can prevent that the user sees the sheet during that time by setting Application.ScreenUpdating = False
. To be sure that the sheet is set to invisible in any case (and ScreenUpdating is enabled again), use an error handler.
Sub exportSheet()
Application.ScreenUpdating = False
With ThisWorkbook.Sheets(2)
On Error GoTo ExportError
.Visible = True
.Range("A1:G103").ExportAsFixedFormat Type:=xlTypePDF, Filename:="(your path here)", OpenAfterPublish:=False
ExportError:
.Visible = False
Application.ScreenUpdating = True
End With
End Sub